Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whether a FormControl value can be an array?

I am working on Angular Reactive form. This is my component class code:

ngOnInit(){
        this.reviewForm = this.fb.group({            
            'controlArray': new FormArray([])
        });        
        this.showDefaultForm();                     
    }

addForm() {
    (<FormArray>this.reviewForm.get('controlArray')).push(this.fb.group({
        controlType: control.controlType,
        options: control.options,

    }));
}

I am getting TypeError: this.validator is not a function with this. I think its due to assigning a string array (i.e. control.options) as value to FormControl. If I make it a FormArray then this error resolves, but I am having issue to handle it as FormArray in template. Please tell if I don't use FormArray, can I assign a string array as value to FormControl? If no then how to handle it as FormArray in template. Thanks

like image 220
Waleed Shahzaib Avatar asked Dec 12 '17 08:12

Waleed Shahzaib


People also ask

How do you know if FormControl is invalid?

Wether it be nested by FormArray-s or FormGroup-s. Just input the top level formGroup and it will return all the FormControls that are invalid.

What is the difference between FormGroup and FormControl?

FormGroup is used with FormControl to track the value and validate the state of form control. In practice, FormGroup aggregates the values of each child FormControl into a single object, using each control name as the key.

Can I use FormControl without FormGroup?

Sometimes, we don't need a FormGroup, as our form might only consist of a single form control. Think of a search field that let's you search for products in an e-commerce application. Technically, we don't even need a <form> element for that.

Is FormControl an observable?

Both FormControls and FormGroups expose an observable called valuesChanged . By subscribing to this observable we can react in real-time to changing values of an individual form control, or a group of form controls.


1 Answers

Finally I solved it, and the answer is yes. A FormControl's value can be an array. But for this you must have to enclose the value with in square brackets [ ]. Moreover, for simple values(Non arrays) these Square brackets are optional, meaning you may enclose the value within or without square brackets.

Code explanation:

(<FormArray>this.reviewForm.get('controlArray')).push(this.fb.group({
        controlType: control.controlType,
        options: [control.options], //previously I was not using square brackets with options value i.e. options: control.options which was wrong.

    }));
like image 91
Waleed Shahzaib Avatar answered Oct 13 '22 03:10

Waleed Shahzaib