angular - 如何阻止 Angular @ViewChild() 创建新的组件实例?
问题描述
我希望我的父组件在子组件(绘图组件,它将 RaphaelJS 对象附加到容器)中执行方法。但是,我不断收到浏览器错误,说该对象尚未实例化。将方法调用移至子类消除了错误,这似乎表明该组件正在由父类中的 @ViewChild() 重新实例化。
我希望父母在孩子中调用绘图方法,我想知道是否有更好的方法来做到这一点。我提出的一些想法是:
- 将子类实现为服务
- 创建一个非 Angular-ee 静态类或单例,然后调用它
- 重做子类以将其所有对象存储在服务中并在每个 ngOnInit() 上重绘所有对象
解决方案
我通过将 Raphael 初始化移动到 ngOnInit() 方法,然后将父组件中的 @ViewChild() 调用移动到 ngAfterViewInit() 方法找到了解决方案。这样,子组件将有足够的时间来完全初始化并在父组件开始调用子组件中需要 Raphael 的绘图方法之前生成其 Raphael 对象。
子组件:
@Component({
selector: 'app-g-view',
template:
`<div
id="conP"
class="container-fluid"
style="width:600px;height:600px;"
>
</div>`,
styleUrls: ['./gview.component.css']
})
export class GVComponent implements OnInit, AfterViewInit{
private paper: Raphael;
constructor() {}
ngOnInit() {
this.paper = Raphael("conP", "100%", "100%");
console.log(this.paper);
let border = this.paper.rect(0,0,"100%","100%");
border.attr({fill:"white"});
console.log(border);
}
父组件:
@Component({
selector: 'app-par',
templateUrl: './par.component.html',
styleUrls: ['./par.component.css'],
})
export class ParComponent implements OnInit, AfterViewInit {
@ViewChild(GVComponent) _gv: GVComponent;
constructor(){}
ngAfterViewInit(){
console.log(`testing child component after init: ${this._gv}`);
this._gv.testMethod();
}
推荐阅读
- javascript - 是否有已知的算法来检测确保形状连续性所需的像素?
- javascript - 如何从特定屏幕中删除 TabNavigatorBar
- mysql - 返回 MySQL 中每天最后一个已知值的时间序列的值
- amazon-web-services - 即使在成功删除同一条消息后,AWS FIFO SQS 队列消息也会消失
- python - 如何忽略 Python 中的一个特定异常?
- reactjs - 如何在同一个域下为移动端和网络端的移动应用程序渲染两个不同的应用程序?
- c++ - 表达式:不能增加值初始化的迭代器(调试中的错误,但不是在发布模式下 - Visual Studio)
- c++ - 数组中第一个 0 之后的所有元素的总和
- python - 三角矩阵的广播求解
- spring-webflux - 带有 Spring Webflux 的 Sleuth 注释给出 CglibAopProxy 警告