【发布时间】:2018-01-30 14:48:43
【问题描述】:
我是 Angular2(或 4?)的新手,正在学习基础知识..
在Forms/Reactive Forms - 添加地址数组没有问题。
但是尝试将验证器添加到地址子元素不起作用:
这是我的表单构建:
constructor(
private fb: FormBuilder
){
this.createForm();
}
createForm() {
this.heroForm = this.fb.group({
name: ['', [Validators.required, Validators.minLength(6)]],
secretLairs: this.fb.array([
this.fb.group({
street: ['', [Validators.required, Validators.minLength(6)]],
city: [''],
state: ['', Validators.required],
zip: ['']
})
]),
power: ['',Validators.required],
sidekick: ''
});
}
get secretLairs(): FormArray {
return this.heroForm.get('secretLairs') as FormArray;
}
和(部分)我的模板:
<div formArrayName="secretLairs" class="well well-lg">
<b class=header>Secret Lairs</b>
<div *ngFor="let address of secretLairs.controls; let i=index" [formGroupName]="i" >
{{ showMe(i, address.controls.street) }}
<h4>Address #{{i + 1}}</h4>
<div style="margin-left: 1em;">
<div class="form-group">
<label class="center-block">Street:</label>
<input class="form-control" trim formControlName="street">
<label class="center-block">City:</label>
<input class="form-control" formControlName="city">
<label class="center-block">State:</label>
<select class="form-control" formControlName="state">
<option *ngFor="let state of states" [value]="state">{{state}}</option>
</select>
<label class="center-block">Zip Code:</label>
<input class="form-control" formControlName="zip">
</div>
</div>
<br>
</div>
<button (click)="addLair()" type="button">Add a Secret Lair</button>
</div>
ShowMe 功能:console.logs the street-formControl
- 在验证器和 asyncValidator 中都显示为 null..?
实际上,地址元素没有(无效)验证发生
- 其他验证器(以及其他一切)完美运行。
我错过了什么?
【问题讨论】:
-
您可以尝试在您的街头物品上使用 Validator.compose。 Validators.compose([]) 和 new FormControl: street: new FormControl('', Validators.compose(Validators.required, Validators.minLength(6))) 等
-
Nope => street: new FormControl('', Validators.required) => 没有区别:validator:null - 一个空的 street-field 仍然是 ng-valid。还尝试了 compose( double ) - no validator..?
-
一切正常plnkr.co/edit/RpcfJZSZToF5UWoKzdLh?p=preview尝试在
Street字段中输入 -
@yurzui - 是的。我的问题是:在获取数据(ngOnChanges)时,我将 formArray 替换为一个新的,其中控件仅包含值 - 没有验证器:(“自动创建”与addresses.map(address => this.fb.group (地址))
标签: angular angular2-template angular2-forms angular2-formbuilder