简体   繁体   English

(TS)尝试使用ViewChild获得子组件访问权时出现(Unused Label)错误

[英](TS) Unused Label error when trying to get child component access using ViewChild

Im facing a trouble when trying to get access of a child component in parent component. 我在尝试访问父组件中的子组件时遇到麻烦。 I imported the components and tried to declare ViewChild method on the nginit. 我导入了组件,并尝试在nginit上声明ViewChild方法。 But when I specify the variable name it says unused label. 但是,当我指定变量名称时,它表示未使用的标签。 Sorry Im a very beginner with Angular 对不起,我是Angular的初学者

Here is the code snippet in which you can see the error. 这是您可以在其中看到错误的代码段。 I need that userListComponent in another function to reinitialise that component by calling its function. 我需要另一个函数中的userListComponent来通过调用其函数来重新初始化该组件。 But because of this error I dont have access into that component. 但是由于这个错误,我无法访问该组件。

在此处输入图片说明

Look at the documentation for the @ViewChild directive . 查看@ViewChild指令文档 Such directive is used in the body of the class, when you define the userListComponent field, not inside the ngOnInit method. 当您定义userListComponent字段时,此类指令用于类的主体中,而不是在ngOnInit方法中。 So just move 所以就移动

@ViewChild(UserListComponent) userListComponent: UserListComponent

outside ngOnInit. 在ngOnInit之外。

You need to declare the 您需要声明

@ViewChild(UserListComponent) userListComponent: UserListComponent

outside of ngOnInit function. ngOnInit函数之外。 Your userListComponent will be initialized in the ngAfterViewInit lifecycle event. 您的userListComponent将在ngAfterViewInit生命周期事件中初始化。

export class TemplateCategoryNewComponent implements OnInit, AfterViewInit {

   @ViewChild(UserListComponent) userListComponent: UserListComponent

   ngOnInit() { ... }

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM