Search code examples
angularplunker

Need to make a call between multiple components in Angular 2


I am trying to make an angular 2 project and need to make a call between multiple components. something like this

<ParentComponent>
    <ChildComponent>
        <ChildComponent 1>
        </ChildComponent 1>
    </ChildComponent> 
</ParentComponent>

I am trying to share information between ParentComponent and ChildComponent by using a component reference and trying to access properties and methods from the parent template. I am able to see the field names of all three components in one form but not able to access the value of childComponent in my parent form.

Form Value:

enter image description here

Here is my plunker

I am new to angular 2. Please help me how we can do this.


Solution

  • You need to build your whole form in your parent, and then just pass the inner FormGroups to the child and grandchild. So your parent build the whole form:

    ngOnInit() {
        this.myForm=this._fb.group({
            subAppName: ['', [Validators.required]],
            vendorDetails: this._fb.group({
             buildType: [''],
             primaryLang: [''],
             product: this._fb.group({
               vendorName: [''],
               productName: ['']
             })
           }),
            subAppType:['', [Validators.required]],
        });
    }
    

    And from your parent, pass the vendorDetails group to vendor component:

    <subapp-vendor #vendortest [vendorDetails]='myForm.controls.vendorDetails'></subapp-vendor>
    

    and use @Input in vendor for the formgroup:

    @Input() vendorDetails: FormGroup;
    

    and use that formGroup name in your view as well as the formcontrolnames you defined in the parent. Here you also pass the inner formGroup to the child component of this childcomponent, just like you did from the parent:

    <div [formGroup]="vendorDetails">
          <label>Built Type</label>
          <div class="radio" *ngFor="let buildType of buildTypes">
            <label>
              <input type="radio" formControlName="buildType" [value]="buildType.value">
              {{buildType.display}}
            </label>
        </div>
    
      <subapp-product #producttest [product]="vendorDetails.controls.product"></subapp-product> 
        <label>Primary Language</label>
        <input type="text" class="form-control" formControlName="primaryLang">
      </div>
    

    aaaand then of course use @Input and the formGroup product in the view in product component just like above.

    Here's your forked plunker