如何停止Angular @ViewChild()创建新的组件实例?

时间:2018-09-07 04:25:00

标签: angular oop raphael

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

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

  • 将子类别作为服务实现
  • 创建一个非Angular-ee静态类或单例,然后调用它
  • 重做子类以将其所有对象存储在服务中,并在每个ngOnInit()上重绘所有子类

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,方法是将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();
}