使用 Angular 和 Reactive 表單構建器創建應用程式。
StackBlitz 示例
該表單是預先填充的,并且在我form.array用來根據資料構建動態控制元件串列的表單中。我已禁用這些欄位,因為我希望我的表單最初是只讀的。我有一個.enable在控制元件上觸發的按鈕,但是作為 中的動態控制元件form.array,我不確定如何在不指定所有控制元件索引值的情況下啟用這些控制元件。
.ts 檔案
public createForm() {
this.service.getmodel().subscribe((response) => {
this.model = response;
this.form = this.fb.group({
type: new FormControl({ value: null, disabled: !this.isOwner }),
items: this.fb.array(
this.model.items.map((x) =>
this.buildFields(x)
)
),
});
});
}
buildFields(x: any): FormGroup {
return new FormGroup({
name: new FormControl({ value: x.name, disabled: !this.isOwner }),
description: new FormControl({
value: x.description,
disabled: !this.isOwner,
}),
code: new FormControl({ value: x.code, disabled: !this.isOwner }),
});
}
enable() {
this.isOwner = true;
const controls = ['type', 'items.description'];
controls.map((x) => {
this.form.get(x).enable({ onlySelf: true });
});
}
我正在啟用啟用文本輸入欄位的控制元件“型別”,對于 form.array 中的專案,我剛剛添加了“items.description” - 盡管我知道這是不正確的,因為該值不存在。它類似于“items[0].description”,但 [0] 可以是由資料長度確定的任何值。
html檔案
<div *ngIf="form">
<form [formGroup]="form">
<textarea
formControlName="type"
name="type"
#type
class="form-control"
id="type"
rows="6"
></textarea>
<div formArrayName="items">
<div
*ngFor="let orgs of form.controls['items']?.controls; let i = index"
[formGroupName]="i"
>
<input formControlName="name" placeholder="Item name" />
<input formControlName="description" placeholder="Item description" />
<input formControlName="code" placeholder="Item price" />
</div>
<button type="button" class="btn btn-success" (click)="enable()">
Enable
</button>
</div>
</form>
<!-- <p>{{ form.value.items}}</p> -->
</div>
最終目標是使 formControlName="name/description/code"
StackBlitz 示例
uj5u.com熱心網友回復:
如果我理解正確,您將成功啟用“型別”但未能啟用名稱/描述/代碼。
請記住,您的主 FormGroup 不包含任何名稱/描述/代碼,它包含另一個名為 items 的 FormGroup,其中包含您的控制元件。首先從主表單中獲取子表單組,然后您就可以訪問表單控制元件??。
用這個替換啟用:
enable() {
this.isOwner = true;
this.form.get('type').enable({ onlySelf: true });
let items = this.form.get('items') as FormArray;
items.controls.forEach(c => {
c.enable({onlySelf: true});
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/369143.html
標籤:javascript 有角的 打字稿 角反应形式
