[英](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.