Angular reactive forms, adding and removing fields?

前端 未结 4 891
孤街浪徒
孤街浪徒 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:08

    The FormGroup API exposes methods such as addControl and removeControl which you can use to add or remove controls from your form group after it has been initialized.

    An example using these methods might look like:

    formMode: 'add' | 'update';
    userForm: FormGroup;
    
    ngOnInit() {
      this.form = this.formBuilder.group({ 
        firstName: [''],
        lastName: ['']
      });
    }
    
    changeMode(mode: 'add' | 'update') {
      if (mode === 'add') {
        if (!this.form.get('firstName')) {
          this.form.addControl('firstName');
        }
        this.form.removeControl('lastName');
      } else {
        if (!this.form.get('lastName')) {
          this.form.addControl('lastName');
        }
        this.form.removeControl('firstName');
      }
    }
    
    onChange(event: 'add' | 'update') {
      this.changeMode(event);
    }
    

    You'll probably want your DOM to reflect the state of your form by adding *ngIf checks based on the existence of a given control:

     
    

提交回复
热议问题