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