在Angular中,要访问父组件中的子组件变量,可以使用@ViewChild装饰器。
假设有一个父组件ParentComponent和一个子组件ChildComponent,其中ChildComponent有一个变量childVariable需要在父组件中访问。
首先,在父组件的模板中定义子组件,并使用ng-template包裹:
然后,在父组件的类中使用@ViewChild装饰器来获取子组件的实例:
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent-component',
template: `
`
})
export class ParentComponent {
@ViewChild(ChildComponent) childComponent: ChildComponent;
ngAfterViewInit() {
// 父组件中可以访问子组件的变量
console.log(this.childComponent.childVariable);
}
}
在父组件的ngAfterViewInit钩子函数中,可以访问子组件的变量childVariable。
请注意,只有在ngAfterViewInit钩子函数触发之后,才能访问子组件的变量。这是因为ngAfterViewInit在子组件视图初始化之后才会被调用。
以上就是在Angular 8中访问父组件的ng-template中使用的子组件变量的解决方法。