未引发ngSubmit事件

时间:2018-10-18 11:51:21

标签: angular

我有以下简单的角度模板驱动形式,当我使用Angular材质组件时不起作用(ngSubmit事件似乎未引发),但在使用自举样式控件时同样起作用...数据模型绑定在两种情况下均有效,但是对于材料组件,不会调用“ authenticateUser”方法。我肯定在这里遗漏了一些东西。

<div class ="login-container">
<form #loginForm="ngForm" (ngSubmit)="authenticateUser(loginForm)" >
    <div>
        <mat-form-field >
          <input matInput placeholder="Username" name="username" [(ngModel)]="username"  required>
        </mat-form-field>
    </div>
    <div>
        <mat-form-field>
          <input matInput placeholder="Password" name="password" [(ngModel)]="password" type="password" required>
        </mat-form-field>
    </div>  
</form>
<button mat-raised-button color="primary">Login</button>
<div style="margin-top: 5%">
    <a routerLink="/changepassword">Change Password</a>
</div>    

角度生成的表单模型:{{loginForm.value | json}}

谢谢

jcm

3 个答案:

答案 0 :(得分:0)

submit button必须在form

<div class ="login-container">
<form #loginForm="ngForm" (ngSubmit)="authenticateUser(loginForm)" >
    <div>
        <mat-form-field >
          <input matInput placeholder="Username" name="username" [(ngModel)]="username"  required>
        </mat-form-field>
    </div>
    <div>
        <mat-form-field>
          <input matInput placeholder="Password" name="password" [(ngModel)]="password" type="password" required>
        </mat-form-field>
    </div>  
    <button mat-raised-button color="primary" type="submit" >Login</button>
</form>

<div style="margin-top: 5%">
    <a routerLink="/changepassword">Change Password</a>
</div>   

答案 1 :(得分:0)

按钮类型应为submit,并且应在表单内部

<form #loginForm="ngForm" (ngSubmit)="authenticateUser(loginForm)" >
    <div>
        <mat-form-field >
          <input matInput placeholder="Username" name="username" [(ngModel)]="username"  required>
        </mat-form-field>
    </div>
    <div>
        <mat-form-field>
          <input matInput placeholder="Password" name="password" [(ngModel)]="password" type="password" required>
        </mat-form-field>
    </div>  

<button mat-raised-button color="primary" type="submit">Login</button>
</form>

答案 2 :(得分:0)

在您的.html中,

<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm)" id="ngForm">
  ....
</form>

<button form="ngForm" mat-icon-button type="submit" [disabled]="myForm.invalid">

在您的.ts中,

request : any;

onSubmit(form: FormGroup) {
    this.request = this.myForm.value;
    if (form.value.id != null) {
      this.service
        .put(this.request )
        .subscribe(
          () => {
          },
          err => {
            console.log("Error Occurred." + JSON.stringify(err));
          }
        );
    } else {
      this.service
        .create(this.request)
        .subscribe(
          () => {
            this.snackBarService.success("Successfully saved.");
          },
          err => {
            console.log("Error Occurred" + JSON.stringify(err));
          }
        );
    }
  }