提交论坛时没有显示儿童形式的角度材料2垫错误

时间:2018-01-27 10:32:12

标签: javascript angular forms angular-material2

使用父表单中的输入放置子组件并使用invalidation提交将不会仅在父组件中显示子组件中的错误。只有点击输入时,才会显示孩子的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);
  }
}

2 个答案:

答案 0 :(得分:2)

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

当提交父表单时,手动设置子项&#34; newPassword&#34;控制为&#34;触及&#34;

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

答案 1 :(得分:0)

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

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();
    });
  }
}