How to append new FormGroup or FormControl to form

前端 未结 4 1143
灰色年华
灰色年华 2021-01-31 15:28

I have the following form in Angular created with FormBuilder:

constructor(private fb: FormBuilder) {
    this.myForm = fb.group({
             


        
4条回答
  •  无人及你
    2021-01-31 16:04

    In my opinion, you could just use an intermediate variable for this purpose. Take a look at the next example:

      constructor(private fb: FormBuilder) {
        let group = {
          'name': ['', [Validators.required]],
          'surname': ['', [Validators.required]],
          'email': ['', [Validators.required]]
        };
    
        let middlename = true;
    
        if(middlename) {
          group['middlename'] = ['', [Validators.required]];
        }
    
          this.myForm = fb.group(group);
        }
    

    Also, it would a better idea to transfer a form initiation in ngOnInit hook, instead of component constructor.

提交回复
热议问题