Angular 4 array validation

后端 未结 1 703
广开言路
广开言路 2021-02-04 15:30

I need help with formArray validation in reactive form. I want validate each item in array, but i have no idea how can i do that. Thanks.

<

1条回答
  •  青春惊慌失措
    2021-02-04 16:19

    Your getters for name and info actually don't target the specific form controls, since your person is a formArray, for example this.form.get('person.name'); does not exist in your form. What you need to do, is use the iteration for each formgroup and target that group with its controls, so your template should look like this:

    Required

    DEMO


    Furthermore a suggestion is, that you can shorten your code a bit and remove a method that isn't really needed for initializing/adding formgroup to your array, so here I removed the addNewRow, initItemRows can be called when you want a new row added.

    this.form = this.fb.group({
      person: this.fb.array([])
    });
    this.initItemRows();
    
    initItemRows() {
      let ctrl = this.form.controls.person;
      ctrl.push(this.fb.group({
        name: ['', Validators.required],
        info: ['', Validators.required]      
      }))
    }
    

    0 讨论(0)
提交回复
热议问题