Angular reactive forms, adding and removing fields?

前端 未结 4 883
孤街浪徒
孤街浪徒 2021-02-14 10:27

while building crud app in angular 5 I\'ve come across with a question, how can I use the same form builder but change what form controls I get depending on what I want, adding

4条回答
  •  天涯浪人
    2021-02-14 11:14

    This is the most simple replication of add/remove for conditional angular form controls.

    Seeing that you have a form with a checkbox control named someCheckboxControl watch for its boolean changes to add/remove the other control.

    ngOnInit() {
       this.form.controls['someCheckboxControl'].valueChanges.subscribe(someCheckboxControlVal => {
           if (someCheckboxControlVal) {
               this.form.addControl('SomeControl', new FormControl('', Validators.required));
           } else {
               this.form.removeControl('SomeControl');
           }
       });
    }
    

    HTML

    
    

提交回复
热议问题