gpt4 book ai didi

Angular2 表单被提交而不是运行 onSubmit() 方法

转载 作者:太空狗 更新时间:2023-10-29 18:26:30 26 4
gpt4 key购买 nike

我有以下组件:

模板

<div class="hide" id="login-contents">
<form *ngIf="!current_user" role="form" (ngSubmit)="onSubmit()" #loginForm="ngForm">
<div class="form-group">
<label for="username">Username</label>
<input type="text"
#username
id="username"
class="form-control"
required
placeholder="Username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password"
#password
id="password"
class="form-control"
required
placeholder="Password">
</div>
<button type="submit"
class="btn btn-block btn-primary"
[disabled]="!loginForm.form.valid">Login</button>
</form>
</div>

组件 typescript

@Component({
selector: 'login-form',
templateUrl: '/app/form.login.html'
})
export class LoginFormComponent implements OnInit {
submitted = false;

ngOnInit() {
console.log("Form initialised");
}

onSubmit(event: any, username: string, password: string) {
event.preventDefault();
console.log('onSubmit');
this.submitted = true;
return false;
}
}

根据onInit东西(出于调试原因添加),表单组件被加载(当然,正如我看到的表单本身)。 preventDefault()电话和return false是我试图阻止在我按下登录按钮时发生的实际提交(因此,整个页面重新加载)。此外,即使未填写表单(因此无效),登录按钮也不会被禁用。

我已经尝试使用 <button type="button">而不是 type="submit" ,但是 onSubmit()方法不会被调用。如果我移动 (ngsubmit)="onSubmit()" 会发生同样的情况(或者更像是不会发生)到按钮 (click)="onSubmit()" .我开始怀疑问题出在更深的地方,甚至不在这个组件中。

我可能会错过什么?我正在使用 2.0.0-rc.6 .

最佳答案

使用

 <button type="button" (click)="onSubmit()"

代替

 <button type="submit" 

关于Angular2 表单被提交而不是运行 onSubmit() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39331504/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com