【问题标题】:Angular 2: transfer data from parent to childAngular 2:将数据从父级传输到子级
【发布时间】:2017-07-20 14:09:13
【问题描述】:

我有一个带有路由器插座的组件。这个组件有一个选择元素,我通过服务在 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 调用。是否可以在父母和孩子之间共享这些数据?

【问题讨论】:

  • 您是否尝试使用 viewChild() ?
  • 不知道viewChild是什么,去看看,谢谢
  • ViewChild 通过在父模板中声明子组件来工作?如果是这样,那么我认为它在这种情况下不起作用,我只有路由器插座。

标签: angular components communication interaction


【解决方案1】:
export class parentComponent  {

   @ViewChild(ChildOneComponent)
   private childOneComponent: ChildOneComponent;

   @ViewChild(ChildTwoComponent)
   private childTwoComponent: ChildTwoComponent;

   let date = this.childOneComponent.method1;

}

这个method1()是在你的子组件中为get方法定义的。你必须在你的父组件中导入子组件。

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

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-15
      • 2015-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      相关资源
      最近更新 更多