单击 MatFormFieldControl 中的按钮触发 Angular 4 中表单上的提交操作

Pat*_* M. 4 angular angular4-forms

我开发了一个自定义组件(app-mat-avatar)用作头像选择(见图)。它由一个带有图片和 2 个按钮的大 div 组成。一个是编辑,另一个是擦除。我按照创建自定义表单字段控件中的Angular 指南构建了它 在此处输入图片说明

这是我使用它的形式:

<form name="detailsForm" [formGroup]="detailsForm" (submit)="submitDetails($event)">
    <app-mat-avatar [size]="150" formControlName="photoURL"></app-mat-avatar>
    <input matInput type="email" placeholder="Email" formControlNamesss="email" disabled value="{{detailsForm.get('email').value}}">
.....

    <div flex layout="row" layout-align="end center" class="fullWidth pad-right-sm">
        <button mat-button mat-raised (click)="resetDetails()" class="push-right-xs" [disabled]="busy">Reset</button>
        <button type="submit" mat-button mat-raised-button color="primary" [disabled]="detailsForm.invalid || busy">Save</button>
    </div>
</form>
Run Code Online (Sandbox Code Playgroud)

这是支持表单所在页面组件的代码:

@Component({
  selector: 'app-my-info',
  templateUrl: './my-info.component.html',
  styleUrls: ['./my-info.component.sass']
})
export class MyInfoComponent implements OnInit, OnDestroy {

  detailsForm = new FormGroup({
    uid: new FormControl(''),
    photoURL: new FormControl(''),
    firstName: new FormControl('', [Validators.required, Validators.minLength(2)]),
    lastName: new FormControl('', [Validators.required, Validators.minLength(2)]),
    sex: new FormControl('', [Validators.required]),
    email: new FormControl('', [Validators.required, Validators.email]),
    licenseLocal: new FormControl(''),
    licenseNational: new FormControl(''),
    cellPhone: new FormControl(''),
  });

........

  ngOnInit() {
    fetchUserFromDatabase.subscribe( me => {
      if (!me) {return; }
      this._currentUser = me;      
      this.resetDetails();

    }));
  }

  resetDetails() {
    const user = {
      email : this.currentUserCopy.email,
      photoURL: this.currentUserCopy.photoURL,
      firstName: this.currentUserCopy.firstName,
      lastName: this.currentUserCopy.lastName,
      licenseLocal: this.currentUserCopy.licenseLocal || '',
      licenseNational: this.currentUserCopy.licenseNational || '',
      sex: this.currentUserCopy.sex,
      cellPhone: this.currentUserCopy.cellPhone || ''
    };
    this.detailsForm.patchValue( user );
  }


  submitDetails(event) {
    // console.log(event);
    this._currentUser.createFromFirebaseData(this.detailsForm.value);
    this._db.UpdateUser(this._currentUser)
    .then( result => {
      this.busy = false;
      this._popUp.showInfo('Perfil guardado');
    })
    .catch( error => {
      this.busy = false;
      this._popUp.showError(error);
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

一切正常,除了当我单击 app-mat-avatar 组件的按钮之一时,该submitDetails方法被触发。

我试图添加event.stopPropagation();按钮单击调用的方法的第一行,但没有效果。

知道为什么会发生这种情况吗?

Son*_*300 9

添加type="button"到模板中的重置按钮以防止提交

  • 我没有确切的答案,但多次遇到问题,似乎当您不指定类型时,它认为是提交按钮 (2认同)