问题描述
我想要做的是根据其是否有效向每个输入的父 div 添加一个无效类。
在表单的其余部分,我可以像这样访问输入字段控件:
<div
class="form-group focus"
[ngClass]="!recipeForm.controls.name.valid ? 'invalid' : ''"
>
<input
type="text"
id="name"
class="form-control"
formControlName="name"
/>
<label for="name" class="shrink">Name</label>
</div>
[ngClass]="!recipeForm.controls.name.valid ? 'invalid' : ''"
但是我有一个包含名称/数量控制的成分的 FormsArray。我如何访问这些成分?`
get controls() {
// a getter!
const FormArray = (<FormArray>this.recipeForm.get('ingredients')).controls;
for (let i = 0; i < FormArray.length; i++) {
console.log(FormArray[i]);
}
return FormArray;
}`
如果我做 FormArray[i].value.name 它工作但如果我做 FormArray[i].controls.name 它说属性 'controls' 不存在于类型 'AbstractControl' 即使我可以看到有带有名称和数量的控件属性。
我的 ts 文件:
onAddIngredient() {
(<FormArray>this.recipeForm.get('ingredients')).push(
new FormGroup({
name: new FormControl(null,Validators.required),amount: new FormControl(null,[
Validators.required,Validators.pattern(/^[1-9]+[0-9]*$/),]),})
);
}
HTML 模板:
<div class="form-ingredients" formArrayName="ingredients">
<div
class="form-amount-group"
*ngFor="let ingredientCtrl of controls; let i = index"
[formGroupName]="i"
>
<div class="form-group focus">
<input class="" type="text" id="name" class="form-control" />
<label for="name" class="shrink">Name</label>
</div>
<div class="form-group focus amount">
<input
type="number"
class="form-control"
formControlName="amount"
/>
<label for="name" class="shrink">Amount</label>
</div>
<div class="operations">
<div class="button plus">
<button><i class="fas fa-plus"></i></button>
</div>
<div class="button minus">
<button><i class="fas fa-minus"></i></button>
</div>
</div>
<button class="btn btn-sm" title="Delete Ingredient">
<i class="fa fa-trash"></i>
</button>
</div>
</div>
解决方法
尝试使用:
您在控件中循环。因此,您的循环元素就是控件。
app.component.ts
get controls() {
return (this.recipeForm.get("ingredients") as FormArray).controls;
}
addIngredient() {
const creds = this.recipeForm.controls.ingredients as FormArray;
creds.push(
this.fb.group({
name: [null,Validators.required],amount: [
null,[Validators.required,Validators.pattern(/^[1-9]+[0-9]*$/)]
]
})
);
}
app.component.html
<form [formGroup]="recipeForm">
<input type="checkbox" formControlName="name" /> Published
<div *ngIf="recipeForm.controls.name.value">
<h2>ingredients</h2>
<button (click)="addIngredient()">Add</button>
<div formArrayName="ingredients">
<div *ngFor="let ingredient of controls; let i = index">
<div [formGroup]="ingredient">
<input placeholder="Name" formControlName="name" />
<p>{{ ingredient.get("name").valid }}</p>
<input placeholder="Amount" formControlName="amount" />
<p>{{ ingredient.get("amount").valid }}</p>
</div>
</div>
</div>
</div>
</form>
这里的 stackblitz
示例:
https://stackblitz.com/edit/angular-form-array-example-ewyumv?file=src/app/app.component.ts