1

在 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

可以帮我解决这个问题,

谢谢你

4

2 回答 2

1

我想这是因为子组件尚未渲染,您可以使用ngAfterContentInit

这个生命周期钩子应该只在孩子被绘制后被触发,然后你应该能够获得参考。

import { ChildComponent } from  './table/child.component';

export class  ParentComponent implements ngAfterContentInit, OnInit{
  @ViewChild(ChildComponent) child: ChildComponent;

   ngAfterContentInit(){
   console.log(' ngAfterContentInit() : ', this.child.name);
  }

}

让我知道这是否有帮助。

于 2019-06-09T18:23:59.437 回答
0

为确保您的孩子已加载,请使用ViewChildren()并订阅更改。

于 2019-06-09T18:56:05.223 回答