【问题标题】:Multiple components in router-outlet @input decorator not workingrouter-outlet @input 装饰器中的多个组件不起作用
【发布时间】:2018-07-12 22:57:09
【问题描述】:

我的路由器模块 /dashboard 中有一条路由。在这条路线中,我有多个组件,包括一个父组件和几个子组件。我使用 @Input 装饰器将数据(tablesPanorama(对象数组))从名为 TischplanComponent (tischplan.component.ts) 的父组件传递到名为 DepartmentsComponent (departments.component.ts) 的子组件。

app.module.ts

const appRoutes: Routes =  [
  {path: '', component: LoginComponent},
  {path: 'login', component: LoginComponent},
  {path: 'dashboard', component: TischplanComponent, canActivate: [AuthGuard]},
  {path: 'register', component: RegisterComponent},
  {path: 'profile', component: ProfileComponent, canActivate: [AuthGuard]}
];

导入:[RouterModule.forRoot(appRoutes)]

app-component-html

这是路由器插座所在的位置

<router-outlet></router-outlet>

tischplan.component.html

 <app-departments [tablesPanorama]="tablesPanorama"</app-departments>

departments.component.ts

@Input('tablesPanorama') tablesPanorama: Table[];

不幸的是,数据没有传递给子组件。是什么导致了这个问题?如果我在构造函数中 console.log this.tablesPanorama 我得到未定义:

  constructor(private tischplanService: TischplanService) {
    console.log("this.tablesPanorama:");
    console.log(this.tablesPanorama);
  }

@Input&lt;router-outlet&gt;之间的连接:

据我了解我的代码,@Input 位于名为 DepartmentComponent 的子组件中,它从父组件 TischplanComponent 传递变量 tablesPanorama,它是 &lt;router-outlet&gt; 中 /dashboard 路由的组件,它位于在 app.component.ts 中。

【问题讨论】:

  • 你到底想做什么,将数据传递给另一个组件,或者你想导航到另一个组件
  • 我只想将 data 传递给另一个组件
  • 只需在组件中导入该组件,然后在构造函数中创建它的对象,然后使用该对象将数据传递给该组件
  • 谢谢。让我试试看。
  • @Input() 在路由器添加的组件上不受支持。目前尚不清楚@Input()&lt;router-outlet&gt; 在您的问题中有何关联。

标签: angular typescript routes components


【解决方案1】:

首先:改变这一行 -->

@Input() tablesPanorama: Table[];

您使用的是@Input,而不是@Viewchild,您不必指定它。

第二:等到视图初始化ngAfterViewChecked 读取您的表格Panorama var

【讨论】:

  • setTimeout(() =&gt; {}, x); 工作。不确定这是否是好的做法。
  • 一点也不,setTimeout() 总是一个可怕的解决方法。 ngAfterViewInit() 不起作用?
  • 所以尝试使用ngAfterViewChecked 而不是 init.. 你会看到这么多控制台日志,这不是问题,是 Angular 仍在监听 DOM 的变化。因此,如果发生这种情况,请不要担心
  • ngAfterViewCheckedworks。非常感谢您的努力!
猜你喜欢
  • 2012-06-29
  • 1970-01-01
  • 2020-06-03
  • 1970-01-01
  • 2020-03-03
  • 2020-11-23
  • 2020-12-01
  • 1970-01-01
  • 2018-05-08
相关资源
最近更新 更多