我有一个带有画布的基本组件。我可以在这个基类的 ngOnInit 方法中将画布填充为纯色。
我有一个继承基础模板的子组件。我尝试从子级的 ngAfterViewInit 方法调用基础的画布填充方法,但它说画布元素为空。
我已输入警报消息,它们会按照我预期的顺序出现。第一个位于基础的 ngOnInit 方法中,第二个位于基础的 fillCanvas 方法中,我从子级的 ngAfterViewInit 方法中调用该方法。
我在 StackBlitz 中有代码:
任何人都可以帮我看看我做错了什么\需要做什么才能实现孩子对画布的填充?
我认为你不需要继承,你可以从该元素的 viewChild 调用该函数,如下所示!
孩子
import { ViewChild } from '@angular/core';
import { Component, AfterViewInit } from '@angular/core';
import { BaseComponent } from '../base/base.component';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
})
export class ChildComponent implements AfterViewInit {
@ViewChild(BaseComponent) base: BaseComponent;
constructor() {}
ngAfterViewInit() {
this.base.fillCanvas();
}
}
子 html
<app-base [templateRef]="childTemplate"></app-base>
<ng-template #childTemplate> Child's extended template </ng-template>