angular 2 remove all items from a formarray

后端 未结 15 1658
清歌不尽
清歌不尽 2020-12-07 15:30

I have a form array inside a formbuilder and i am dynamically changing forms, i.e. on click load data from application 1 etc.

The issue i am having is that all the

15条回答
  •  囚心锁ツ
    2020-12-07 16:11

    Provided the data structure for what you will be replacing the information in the array with matches what is already there you can use patchValue

    https://angular.io/docs/ts/latest/api/forms/index/FormArray-class.html#!#reset-anchor

    patchValue(value: any[], {onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}) : void Patches the value of the FormArray. It accepts an array that matches the structure of the control, and will do its best to match the values to the correct controls in the group.

    It accepts both super-sets and sub-sets of the array without throwing an error.

    const arr = new FormArray([
       new FormControl(),
       new FormControl()
    ]);
    console.log(arr.value);   // [null, null]
    arr.patchValue(['Nancy']);
    console.log(arr.value);   // ['Nancy', null]
    

    Alternatively you could use reset

    reset(value?: any, {onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}) : void Resets the FormArray. This means by default:

    The array and all descendants are marked pristine The array and all descendants are marked untouched The value of all descendants will be null or null maps You can also reset to a specific form state by passing in an array of states that matches the structure of the control. The state can be a standalone value or a form state object with both a value and a disabled status.

    this.arr.reset(['name', 'last name']);
    console.log(this.arr.value);  // ['name', 'last name']
    

    OR

    this.arr.reset([   {value: 'name', disabled: true},   'last' ]);
    console.log(this.arr.value);  // ['name', 'last name']
    console.log(this.arr.get(0).status);  // 'DISABLED'
    

    Here's a forked Plunker demo from some earlier work of mine demoing a very simple utilization of each.

提交回复
热议问题