javascript - 提交论坛时未显示子表单中的 Angular Material 2 垫错误

标签 javascript angular forms angular-material2

将带有输入的子组件放置在父表单中并提交无效将不会仅在父表单中显示子组件中的错误。 child 的 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);
  }
}

最佳答案

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

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

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

关于javascript - 提交论坛时未显示子表单中的 Angular Material 2 垫错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48474876/

相关文章:

Angular2-OnInit : Values returned from Service' subscribe function does not get assigned to Component field/s

html - 单选按钮图像不允许选择值

html - 使用 Web 表单通过 HTTP POST 上传文件的最佳方式是什么?

javascript - 正则表达式 : combine patterns using alternation operator or execute regular expression several times

angular - Angular 中的探查器火焰图未显示我的功能

javascript - 如何使动画关闭与打开相同

javascript - 抽屉菜单表演

javascript - 作为网站的最终用户,有什么方法可以将复选框状态保存在 URL 中吗?

javascript - AngularJS 动态输入值绑定(bind)到数组模型

javascript - 在redux中使用combineReducers时如何修复shape AssertionError?