我已经设置了一个嵌套的表单组。到目前为止一切正常。但是当有嵌套的表单元素时,我不确定如何正确设置验证警报。
发生的一件事是在构建过程中出现错误:“AbstractControl”类型上不存在属性“控件”
这是我的代码:
import { Component, OnInit } from '@angular/core';
import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Reactive Form - Nested FormGroups';
myForm: FormGroup;
constructor(
private fb: FormBuilder
) {}
ngOnInit() {
this.buildForm();
}
buildForm() {
this.myForm = this.fb.group({
user : this.fb.group({
'firstName': new FormControl('', Validators.required),
'lastName': new FormControl('', Validators.required)
}),
'bio': new FormControl()
});
}
}
我的问题是验证查看带有 class="validation-message" 的 div
<hello name="{{ name }}"></hello>
<form [formGroup]="myForm">
<div class="my-box" formGroupName="user">
<label>
First Name
<input type="text" formControlName="firstName">
<div class="validation-message" *ngIf="!myForm.controls.user.controls['firstName'].valid && myForm.controls.user.controls['firstName'].dirty">
This field is invalid
</div>
</label>
</div>
<div class="my-box" formGroupName="user">
<label>
Last Name
<input type="text" formControlName="lastName">
</label>
</div>
<div class="my-box">
<label for="bio" class="block-me">Bio</label>
<textarea formControlName="bio"></textarea>
</div>
</form>
<p>
Data from form: {{ myForm.value | json }}
</p>