首页 > 解决方案 > 如何阻止 Angular @ViewChild() 创建新的组件实例?

问题描述

我希望我的父组件在子组件(绘图组件,它将 RaphaelJS 对象附加到容器)中执行方法。但是,我不断收到浏览器错误,说该对象尚未实例化。将方法调用移至子类消除了错误,这似乎表明该组件正在由父类中的 @ViewChild() 重新实例化。

我希望父母在孩子中调用绘图方法,我想知道是否有更好的方法来做到这一点。我提出的一些想法是:

标签: angularoopraphael

解决方案


我通过将 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();
}

推荐阅读