溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在Angular中使用FormArray來動態(tài)添加或刪除表單控件

發(fā)布時間:2024-06-18 10:29:48 來源:億速云 閱讀:87 作者:小樊 欄目:web開發(fā)

在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)添加或刪除表單控件。

向AI問一下細節(jié)

免責聲明:本站發(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)容。

AI