Dynamically addControl to formgroup Angular 5

后端 未结 3 1115
孤街浪徒
孤街浪徒 2020-12-08 01:51

Trying to dynamically add a new formControl entry to my formGroup in Angular.

method() {
  this.testForm.addControl(\'n         


        
相关标签:
3条回答
  • 2020-12-08 02:01

    Sure, but the second parameters should be a FormControl instance. Something like:

    this.testForm.addControl('new', new FormControl('', Validators.required));
    

    You can also add the validators dynamically if you want with the setValidators method.

    More information here: https://angular.io/api/forms/FormGroup#addControl

    0 讨论(0)
  • 2020-12-08 02:10

    simple use:

      this.testForm.addControl('new', this.fb.group({
          name: ['', Validators.required]
        }));
    
    0 讨论(0)
  • 2020-12-08 02:26

    If you are using FormBuilder for your form, you can also use that for adding a control:

    constructor(private fb: FormBuilder) { }
        
    method() {
      this.testForm.addControl('new', this.fb.control('', Validators.required));
    }
    
    0 讨论(0)
提交回复
热议问题