Angular 2: Add validators to ngModelGroup

前端 未结 3 894
被撕碎了的回忆
被撕碎了的回忆 2021-01-13 23:08

I am using a ngModelGroup directive to group several form inputs together.

In the docs (https://angular.io/docs/ts/latest/api/forms/index/NgModelGroup-d

3条回答
  •  感情败类
    2021-01-13 23:23

    Thanks all for helping me out! I've accepted Silentsod's answer because it was most helpful.

    My final solution was simply building the form using FormBuilder.

    In my component, create the form and add the validator function to it:

    ngOnInit(): void {
        // Validator function:
        let validateMemberList = (group: FormGroup) => {
            let checked = Object.keys(group.controls).reduce((count, key: string) => {
                return count + (group.controls[key].value ? 1 : 0);
            }, 0);
    
            return checked === 0 ? {'minchecked': 1} : null;
        };
    
        this.jobForm = this.formBuilder.group({
            jobTitle: ['', Validators.required],
            // more inputs...
            members: this.formBuilder.group({}, {
                // The 2nd argument is an object with a validator property:
                validator: validateMemberList
            }),
            supportMembers: this.formBuilder.group({}, {
                validator: validateMemberList
            })
        });
    

    Then in my template:

    ...

    This validates the form allowing me to display errors and disable the submit button.

    Thanks all for the help!

提交回复
热议问题