Reputation: 797
I have a form group which was build in ngOninit but later when one of that controls is clicked, I want to add few more controls to that existing form group based on the values got from another API in ngOninit. Below pictures shows the actual requirement. When I click on other role, I want to show other role controls which I've got from an API.
since I'm new to angular2, can anyone help me to get out of this problem?
Upvotes: 2
Views: 3983
Reputation: 537
To add a form control in an already existing form group, you need to:
Add Import into your component/ service
import {FormControl} from "@angular/forms";
create new form-control
const customControl = new FormControl( defaultValue, [Validators.required] );
Attach newly defined form control in the existing form group
this.yourFormGroup.addControl('newControlName', customControl );
Upvotes: 0
Reputation: 2851
// After Initializing the FormGroup
this.FormGroup.addControl(
'firstname',
new FormControl('DefaultName', [Validators.required])
);
<!-- Inside existing Form -->>
<input type="text" formControlName="firstname" />
Upvotes: 0
Reputation: 1
In FormGroup class their's a built in method : addControl
See more in angular documentation : https://angular.io/api/forms/FormGroup#addcontrol
Upvotes: 0
Reputation: 20005
You could add a method that controls and make validations on your form, if that is what you are asking.
Something like:
<button type="submit" (click)="save(f.value, f.valid)">Submit</button>
Where on your save()
method you can validate the form and so on.
More information about form controls in Angular 2: https://scotch.io/tutorials/how-to-deal-with-different-form-controls-in-angular-2
Update:
As you are new to Angular 2, this have to be a must read for you: https://angular.io/docs/ts/latest/cookbook/dynamic-form.html
It is very useful to understand how do dynamic forms behave in Angular2 and how to implement them.
Update 2:
I understood badly your question. If what you want is to add dynamically elements to your form the simplest approach would be to use *ngIf
in order to show/hide elements dynamically.
Example:
<input type="text" *ngIf="showInput"/>
Documentation: NgIf Directive
Upvotes: 0
Reputation: 2763
You can try with below approach.
const arrayControl = <FormArray>this.myForm.controls['formArray'];
let newGroup = this.fb.group({
/// new controls
}
arrayControl.push(newGroup);
Upvotes: 2