您好,登錄后才能下訂單哦!
在Angular中,可以使用FormArray來動態(tài)添加或刪除表單控件。以下是一個簡單的示例,展示如何使用FormArray來實現(xiàn)動態(tài)添加或刪除表單控件:
首先,創(chuàng)建一個包含F(xiàn)ormArray的FormGroup,并在組件中初始化:
import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent {
form: FormGroup;
constructor() {
this.form = new FormGroup({
items: new FormArray([])
});
}
get items() {
return (this.form.get('items') as FormArray);
}
addItem() {
this.items.push(new FormControl(''));
}
removeItem(index: number) {
this.items.removeAt(index);
}
}
然后,在模板中使用FormArray來動態(tài)添加或刪除表單控件:
<form [formGroup]="form">
<div formArrayName="items">
<div *ngFor="let item of items.controls; let i = index;">
<input [formControlName]="i">
<button (click)="removeItem(i)">Remove Item</button>
</div>
</div>
<button (click)="addItem()">Add Item</button>
</form>
在上面的示例中,當用戶點擊“Add Item”按鈕時,會調(diào)用addItem()方法向FormArray中添加一個新的FormControl。當用戶點擊“Remove Item”按鈕時,會調(diào)用removeItem()方法從FormArray中刪除對應(yīng)的FormControl。
通過這種方式,您可以輕松實現(xiàn)在Angular中使用FormArray來動態(tài)添加或刪除表單控件。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。