伙计我需要一些Angular 4反应形式的帮助。我有嵌套的表单组也可以正常工作,除了验证。但是当我尝试在我的html标记中添加一些处理验证时,我的应用程序崩溃了。
我的组件代码如下:
createForm() {
let options: any = {};
for (let option of this.annoucementOptions) {
options[option.title] = new FormControl(false);
}
let optionsFormGroup: FormGroup = new FormGroup(options);
this.annoucementForm = this.fb.group({
address: this.fb.group({
country: ['', [Validators.maxLength(50)]],
state: ['', [Validators.maxLength(50)]],
city: ['', [Validators.required, Validators.maxLength(50)]],
street: ['', [Validators.required, Validators.maxLength(50)]],
apartment: ['', [Validators.required, Validators.maxLength(50)]],
}),
description: this.fb.group({
title: ['', [Validators.required, Validators.maxLength(80)]],
shortDescription: [''],
livingPlaces: [''],
room: [''],
options: optionsFormGroup
}),
priceBlock: this.fb.group({
price: ['', [Validators.required, Validators.maxLength(80)]],
type: ['', [Validators.required, Validators.maxLength(80)]],
}),
});
}
这是我的模板代码:
<form class="form form-lg form-def" *ngIf="annoucementForm" (ngSubmit)="saveDetails(annoucementForm)" name="annoucementForm" [formGroup]="annoucementForm">
<div class="form-block" formGroupName="address">
<h2 class="form-block-heading flag-label primary">Address</h2>
<ul class="row form-list">
<li class="col-md-6 col-lg-4 form-list-item">
<md-input-container class="d-block">
<input type="text" mdInput placeholder="*Country" formControlName="country">
</md-input-container>
<div class="form-error text-danger"
*ngIf="annoucementForm.get('country').touched "
>
<p *ngIf="annoucementForm.get('country').hasError('maxlength')">
*This field be more than 35 characters long.
</p>
</div>
</li>
</ul>
答案 0 :(得分:8)
使用
annoucementForm.get('address.country')
或
annoucementForm.get(['address', 'country'])
而不是
annoucementForm.get('country')