尝试使用ViewChild访问子组件时,(TS)未使用标签错误

时间:2018-01-15 08:18:12

标签: angular

我在尝试访问父组件中的子组件时遇到了麻烦。我导入了组件并尝试在nginit上声明ViewChild方法。但是当我指定变量名称时,它表示未使用的标签。对不起,我是Angular的初学者

以下是您可以在其中查看错误的代码段。我需要另一个函数中的 userListComponent 来通过调用它的函数来重新初始化该组件。但由于这个错误,我无法访问该组件。

enter image description here

2 个答案:

答案 0 :(得分:2)

查看documentation for the @ViewChild directive。当您定义userListComponent字段时,不在ngOnInit方法内部,此类指令用于类的主体。所以移动

@ViewChild(UserListComponent) userListComponent: UserListComponent

在ngOnInit之外。

答案 1 :(得分:1)

您需要声明

@ViewChild(UserListComponent) userListComponent: UserListComponent

ngOnInit函数之外。您的userListComponent将在ngAfterViewInit生命周期事件中初始化。

export class TemplateCategoryNewComponent implements OnInit, AfterViewInit {

   @ViewChild(UserListComponent) userListComponent: UserListComponent

   ngOnInit() { ... }

   ngAfterViewInit() {
      // here `userListComponent` is available
   }

}