【问题标题】:Angular material 2 mat-error in child form not showing when submitting forum提交论坛时未显示子表单中的 Angular 材料 2 mat-error
【发布时间】:2018-07-06 14:11:15
【问题描述】:

将带有输入的子组件放置在父表单中并以无效方式提交将不会仅在父表单中显示子组件中的错误。子项中的 mat-error 只会在单击输入时显示。

用这个父表单复制错误

  @Component({
      selector: 'lyx-parent-form',
      template: `
  <form novalidate autocomplete="off" role="form" [formGroup]="form" (ngSubmit)="onSubmit()">
    <mat-form-field>
     <input type="password" formControlName="currentPassword" matInput placeholder="current password">
     <mat-error *ngIf="form.get('currentPassword').hasError('required')">current required</mat-error>
    </mat-form-field>

    <lyx-child [form]="form"></lyx-child>

    <button type="submit">submit</button>
  </form>`
    })
    export class ParentFormComponent {
      form: FormGroup;
      constructor(fb: FormBuilder) {
        this.form = fb.group({'currentPassword': ['', [Validators.required]]});
      }  
      onSubmit() {}   
    }

子组件

 @Component({
  selector: 'lyx-child',
  template: `
  <div [formGroup]="form">
    <mat-form-field>
      <input type="password" formControlName="newPassword" matInput placeholder="password">
      <mat-error *ngIf="form.get('newPassword').hasError('required')">Password Required</mat-error>
    </mat-form-field>
   </div>  `
})
export class ChildComponent implements OnInit {
  @Input() form: FormGroup;

  ngOnInit(): void {
    const newPassword = new FormControl('', Validators.compose([Validators.required]));
    this.form.addControl('newPassword', newPassword);
  }
}

【问题讨论】:

  • 找到解决这个问题的办法了吗?
  • 不,我认为 Angular 会在他们的更新中修复它,在此之前我会使用你的解决方法谢谢

标签: javascript angular forms angular-material2


【解决方案1】:

在我能够更好地理解父/子表单交互方式之前,这是一种解决方法。

提交父表单时手动设置子“newPassword”控件为“touched”

onSubmit(): void {
  this.form.controls.newPassowrd.markAsTouched({onlySelf: true});
}

【讨论】:

    【解决方案2】:

    我想出了以下适用于任意数量的嵌套表单的解决方案。要使用此指令,只需将 formSubmittedSync 添加到任何子表单组,例如 &lt;div [formGroup]="childForm" formSubmittedSync&gt;

    import { Directive, SkipSelf } from "@angular/core";
    import { FormGroupDirective, ControlContainer } from "@angular/forms";
    
    @Directive({
      selector: '[formSubmittedSync]'
    })
    export class FormSubmittedSyncDirective {
      constructor(
        @SkipSelf() private parentFormGroupDirective: FormGroupDirective,
        private formGroupDirective: FormGroupDirective) {
        this.parentFormGroupDirective.ngSubmit.asObservable().subscribe(() => {
          (this.formGroupDirective as any).submitted = true;
          this.formGroupDirective.ngSubmit.emit();
        });
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-22
      • 2018-06-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 2019-04-28
      • 2020-09-17
      • 2018-03-26
      相关资源
      最近更新 更多