Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
771 views
in Technique[技术] by (71.8m points)

angular - Angular2 patchValue push value into array

Is it It looks like Angular2's FormGroup.patchValue() doesn't push new elements into an array.

For example something like this:

ngOnInit() {

    this.form = this.formBuilder.group({
        animal: [''],
        school: this.formBuilder.group({
            name: [''],
        }),
        students: this.formBuilder.array([this.formBuilder.control('Bob')])
    });

    setTimeout(() => this.form.patchValue({
      animal: 'cat'
      school : {name: 'Fraser'},
      students: ['Bob gets edited', 'This will not show']
    }), 250);

}

Will only update the first element in "students" but it will not insert the second element.

What would I need to do to make it display both elements?

Plunker here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, as silentsod said, it is not possible. Currently, I am using below as an alternative:

        let controlArray = <FormArray>this.form.controls['apps'];           
        this.list.forEach(app => {
                    const fb = this.buildGroup();
                    fb.patchValue(app);
                    controlArray.push(fb);
            });

Angular Team - We need a new function something like PatchArray() that would patch from a collection/object graph. It is a basic use case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...