mahesh peddi
mahesh peddi

Reputation: 797

How to add form controls to the existing form group - angular2

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.enter image description here

since I'm new to angular2, can anyone help me to get out of this problem?

Upvotes: 2

Views: 3983

Answers (5)

Sarthak Maheshwari
Sarthak Maheshwari

Reputation: 537

To add a form control in an already existing form group, you need to:

  1. Add Import into your component/ service

    import {FormControl} from "@angular/forms";
    
  2. create new form-control

    const customControl = new FormControl( defaultValue, [Validators.required] );
    
  3. Attach newly defined form control in the existing form group

    this.yourFormGroup.addControl('newControlName', customControl );
    

Upvotes: 0

Qamar Zaman
Qamar Zaman

Reputation: 2851

In typescript Class (i.e component.ts)


// After Initializing the FormGroup 

this.FormGroup.addControl(
      'firstname',
      new FormControl('DefaultName', [Validators.required])
    );

In HTML template (i.e component.html)

<!-- Inside existing Form -->>

 <input type="text" formControlName="firstname" />

Upvotes: 0

thibaut rebuffet
thibaut rebuffet

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

SrAxi
SrAxi

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

Pramod Patil
Pramod Patil

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

Related Questions