簡體   English   中英

如何清除角反應形式的 FormArray 值?

[英]How to clear the FormArray values in angular reactive form?

在這里,我想讓 FormArray 的長度為零。 (有人提到這個表格一切正常)

profileForm: FormGroup;

ngOnInit() {
   this.profileForm = new FormGroup({
      nod_title: new FormControl(),
      nod_subtitle: new FormControl(null),
      nod_name: new FormControl(null),
      nod_occupation: new FormControl(null),
      nod_description: new FormControl(null),
      nod_tags: new FormArray([new FormControl('hello'), new FormControl('world')]),
    });
  }

 resetTags() {
   if (this.profileForm.value.nod_tags.length) {   // here I tried
     this.profileForm.value.nod_tags.clear();
     console.log(this.profileForm.value.nod_tags)
 }

<button type="button" (click)="resetTags()"> Reset taggs </button>

在這里,我想清空 nod_tags 值並且 console.log() 應該返回一個空數組。

resetTags() ,獲取您需要的FormControl的相應值。 現在你可以調用reset() ,如下所示:

resetTags() {
   this.profileForm.controls['nod_tags'].reset();
}

根據您的評論,要將其設置為空數組,請使用:

resetTags() {
   let arr = <FormArray>this.profileForm.controls['nod_tags'];
   arr.clear();
}
resetTags() {
    const arr = this.profileForm.controls.nod_tags as FormArray;
    while (0 !== arr.length) {
      arr.removeAt(0);
}

這種方式非常有效。 謝謝大家。

我認為這是你想做的方式

resetTags() {
    this.nodTags.clear();
 }

 get nodTags(): FormArray {
   return this.profileForm.get('nod_tags') as FormArray;
 }

我也做了一個小demo

從 Angular 8+ 開始,最好的方法是使用FormArray提供的clear()方法:

// Reset all tags (Angular 8+)
resetTags() {
  const nodTags = this.profileForm.get('nod_tags') as FormArray;

  if ( nodTags.length > 0 )
    nodTags.clear();
}

如果您使用的是 Angular 7 或更低版本,那么 Mizanur 的版本將起作用。 這是使用它的resetTags()方法的修改版本:

// Reset all tags (Angular 7 and below)
resetTags() {
  const nodTags = this.profileForm.get('nod_tags') as FormArray;

  while ( nodTags.length > 0 ) {
      nodTags.removeAt(0);
}

嘗試這個,

 this.form = this._formB.group({ blocks: this._formB.array(["a","b","c"]) }); this.form.controls['blocks'].value.length = 0;

有更簡單的方法可以使 nod_tags 為空!

get nod_tagsArray() {
    return this.profileForm.controls.nod_tags as FormArray;
  }

    this.nod_tagsArray.controls =[];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM