2017-03-04 69 views
1

我正在尝试创建一个角度为2的项目,并且需要在多个组件之间进行调用。像这样需要在Angular 2中的多个组件之间进行调用

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

我试图用一个部件引用,并试图从父模板访问的属性和方法,分享为父级和ChildComponent之间的信息。 我能够在一个表单中看到所有三个组件的字段名称,但无法访问父表单中的childComponent的值。

形态价值:

enter image description here

Here is my plunker

我是新来的角2.请帮我如何才能做到这一点。

+2

使用'@ output'装饰http://learnangular2.com/outputs/ – Smit

+0

您可以更新根据您的plunker例如您的文章**代替父..子。 child1 .. ** – Aravind

回答

1

您需要在父项中构建整个表单,然后将内部FormGroups传递给子项和孙项。因此,父建全的形式:

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

从你的父母,在vendorDetails组传递给供应商的组件:

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

和供应商使用@input为formgroup:

@Input() vendorDetails: FormGroup; 

并在您的视图中使用该formGroup名称以及您在父级中定义的formcontrolnames。在这里你还内formGroup传递给此childcomponent的子组件,就像你从父所做的:

<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那当然使用@input和formGroup product在产品组件的观点,就像以上。

这是你的forked plunker

+0

PS。我建议你改变你的题目和问题内容,​​因为这是关于动态表格和父母 - >孩子 - >孩子的沟通。这是从目前的问题完全不同:) – Alex

+0

谢谢它的工作:) – Niks

+0

你是非常欢迎! :)因为它解决了你的问题,请考虑通过点击这个答案的投票下的灰色滴答接受答案:) https://meta.stackexchange.com/a/5235 – Alex

相关问题