简体   繁体   English

preventDefault()无法正常工作,如何使其正常工作?

[英]The preventDefault() isn't working, how can I make it so, that it works correctly?

The preventDefault() isn't working correctly. preventDefault()无法正常工作。 When I press the Login button, the page refresh's, but with the preventDefault() it shouldn't. 当我按下“登录”按钮时,页面将刷新,但是使用preventDefault()则不会。

I tried it with stopPropagation() , but there was the same problem. 我用stopPropagation()尝试过,但是有同样的问题。

TypeScript: 打字稿:

loginUser(loginevent){
  loginevent.preventDefault()
  const target = loginevent.target
  const username = target.getElementById('username')
  const password = target.getElementById('pasword')
  console.log(username, password)
}

HTML: HTML:

  <form (submit)="loginUser($loginevent)">
    <input type="text" placeholder="Benutzername" id="username">
    <input type="text" placeholder="Passwort" id="password">
    <input type="submit" value="Login">
  </form>

The loginevent.preventDefault() should prevent the page from reloading it, when I press the Login button. 当我按下“登录”按钮时, loginevent.preventDefault()应该阻止页面重新加载。

You'd have to pass $event as an argument and not any other word. 您必须将$event作为参数而不是其他任何单词传递。 $event is a reserved keyword to get the event data. $event是获取事件数据的保留关键字。

Here's what the Angular Docs say: 这是Angular Docs所说的:

The framework passes the event argument—represented by $event—to the handler method, and the method processes it: 框架将事件参数(由$ event表示)传递给处理程序方法,然后该方法对其进行处理:

Try this: 尝试这个:

<form (submit)="loginUser($event)">
  <input type="text" placeholder="Benutzername" id="username">
  <input type="text" placeholder="Passwort" id="password">
  <input type="submit" value="Login">
</form>

I would suggest you should use what angular has to offer, either a template-driven or reactive form. 我建议您应该使用angular提供的内容,无论是模板驱动形式还是反应形式。 We are coding with angular, then why not do it the angular way :) 我们用角度编码,那么为什么不用角度编码呢:)

Template driven: 模板驱动:

<form #f="ngForm" (ngSubmit)="loginUser(f.value)">
  <input type="text" placeholder="Benutzername" name="username" ngModel>
  <input type="text" placeholder="Passwort" name="password" ngModel>
  <button type="submit">Submit</button>
</form>

Here you now pass the form value to your login, which contains your username and password: 现在,您在此处将表单值传递给您的登录名,其中包含您的用户名和密码:

loginUser(values){
  const username = values.username
  const password = values.password
  console.log(username, password)
}

With this, you don't even need to worry about preventDefault() 有了这个,您甚至不必担心preventDefault()

But I would also recommend the reactive way, read more about both template-driven and reactive forms: https://angular.io/guide/forms 但我也建议使用反应式方式,详细了解模板驱动形式和反应式形式: https : //angular.io/guide/forms

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM