javascript - Angular 6 @Viewchild 不适用于延迟加载
问题描述
这是我的代码,它给出了错误无法读取未定义的属性标题。
父组件
import { Child } from './child.component';
@Component({
selector: 'parent',
})
export class ParentComponet implements OnInit, AfterViewInit {
constructor(){}
@ViewChild(Child) child: Child;
ngAfterViewInit(){
console.log("check data", this.child.title)
}
}
而子组件是。
@Component({
selector: 'child',
})
export class ChildComponet {
public title = "hi"
constructor(){}
}
routing.module.ts 就像
{
path: "",
component: ParentComponent,
children: [
{
path: '/child',
component: ChildComponent
}
]
}
并给出错误是
ERROR TypeError: Cannot read property 'title' of undefined(…)
解决方案
我认为您缺少与创建组件相关的“模板”或“模板网址”
父组件
import { ChildComponent } from './child.component'; // {ChildComponent} not {Child} as we are referencing it to the exported class of ChildComponent
@Component({
selector: 'parent',
template: `<child></child>`
})
export class ParentComponet implements OnInit, AfterViewInit {...}
子组件
@Component({
selector: 'child',
template: `<h1>{{ title }}</h1>`
})
export class ChildComponent {...} // Be sure to spell it right as yours were ChildComponet - missing 'n'
根据用户对此线程的说明进行更新
已添加Stackblitz Demo供您参考(检查控制台)
如果您想访问在父组件下呈现的 ChildComponent,<router-outlet>
您可以利用router-outlet 的(激活)支持的属性来实现:
每当实例化新组件时,路由器出口都会发出激活事件
ParentComponent 的模板
@Component({
selector: 'parent',
template: `<router-outlet (activate)="onActivate($event)"></router-outlet>`
})
export class ParentComponent {
onActivate(event): void {
console.log(event); // Sample Output when you visit ChildComponent url
// ChildComponent {title: "hi"}
console.log(event.title); // 'hi'
}
}
结果将根据您父母的孩子下访问的页面而有所不同
如果你访问Child1Component你会得到它的实例
Child1Component {title: "hi"}
如果你访问Child2Component你会得到它的实例
Child2Component {name: "Angular"}
然后这些结果将反映在您 ParentComponent 的 onActivate(event) 控制台上,供您访问
推荐阅读
- many-to-many - 通过在多对多关系查询构建器中添加新记录,为键“PRIMARY”复制条目 […]
- python - 获取 2 张图像之间的差异并标准化结果
- kubernetes - 在不中断服务的情况下重新创建部署
- java - 检查文件是否存在在 Android 中不起作用。总是说文件不存在
- android - Web 应用程序中的 Restful API
- r - renderDT 只显示标题而不显示任何行
- python - ValueError:无法为具有形状“(?,2)”的张量“目标/ Y:0”提供形状(64、4)的值
- c - 从 Linux 编译到 Windows
- spring - Global exception handler across the camel context – covering all routes
- swift - 在 UILabel 中查看带两位小数的数字