【发布时间】:2019-06-09 18:08:12
【问题描述】:
在 Angular 7 中,我有一个包含子组件的组件。但是,我想获取该子组件的副本以在父组件中使用、调用其函数或其他任何内容。
子组件:
@Component({
selector: 'app-child',
template: `
<h1>child</h1>
`,
})
export class ChildComponent {
name = "child";
constructor(){}
}
父组件:
import { ChildComponent } from './table/child.component';
@Component({
selector: 'app-parent',
template: `
<h1>parent</h1>
<app-child></app-child>
`,
})
export class ParentComponent implements AfterViewInit, OnInit{
@ViewChild(ChildComponent) child: ChildComponent;
ngAfterViewInit(){
console.log(' ngAfterViewInit() : ', this.child.name);
}
}
我实际上使用了一个模板 CoreUi https://github.com/coreui/coreui-free-angular-admin-template,这个模板是不同的,因为每个组件都应该有自己的(模块和路由)。
子组件:src/App/views/test/table/child.component.ts
父组件:src/App/views/test/parent.component.ts
请帮我解决这个问题,
谢谢
【问题讨论】:
-
请你也分享你的html代码吗?
-
您的代码是正确的,但我认为您的子组件尚未加载,我需要查看您的 HTML 代码。
-
如果@debabrata-paul-chowdhury 正确,请尝试使用
setTimeout(() => console.log(' ngAfterViewInit() : ', this.child.name),500)。在某些情况下,取决于您的子组件被实例化的位置(例如,在一个对话框中并且您的子组件是动态实例化的),这需要更长的等待时间。如果这是你的情况,setTimeout就足够了,你可以校准它的延迟。