Angular 2:将数据从父级转移到子级

时间:2017-03-01 09:54:11

标签: angular components communication interaction

我有一个带路由器插座的组件。这个组件有一个select元素,我通过服务在ngOnInit上提供一些类别。有3个子路由,其中​​一个导航到也想要使用这些类别的组件。

我的路线看起来像这样

const routes: Routes = [
{ 
  path: 'marketplace',
  component: MarketplaceComponent,
  resolve: { categories: CategoriesResolveService },
  canActivate: [AuthenticatedGuard],
  children: [      
    { path: 'modules', component: ModulesComponent, resolve: { categories: CategoriesResolveService } }      
  ]
}];

这是进行2次http调用以获取类别。如何将此数据传输到子组件?我想避免再做一次http调用。是否可以在父母和孩子之间共享这些数据?

2 个答案:

答案 0 :(得分:0)

export class parentComponent  {

   @ViewChild(ChildOneComponent)
   private childOneComponent: ChildOneComponent;

   @ViewChild(ChildTwoComponent)
   private childTwoComponent: ChildTwoComponent;

   let date = this.childOneComponent.method1;

}

此方法1()在您的子组件中为get方法定义。您必须在父组件中导入子组件。

ChildOneComponent {
  get method1() {
     return this.value//return which value you pass.
  }
}

答案 1 :(得分:0)