Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何阻止Angular@ViewChild()创建新的组件实例?_Angular_Oop_Raphael - Fatal编程技术网

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

如何阻止Angular@ViewChild()创建新的组件实例?,angular,oop,raphael,Angular,Oop,Raphael,我希望父组件在子组件(将RaphaelJS对象附加到容器的绘图组件)中执行方法。但是,我不断收到浏览器错误,说该对象尚未实例化。将方法调用移动到子类可以消除错误,这似乎表明组件正在由父类中的@ViewChild()重新实例化 我希望家长在孩子中调用绘图方法,我想知道是否有更好的方法来实现这一点。我想到的一些想法是: 将子类实现为服务 创建一个非角度ee静态类或singleton并调用它 重做子类以将其所有对象存储在服务中&在每个ngOnInit()上重画所有对象 我找到了一个解决方案,将Rap

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

我希望家长在孩子中调用绘图方法,我想知道是否有更好的方法来实现这一点。我想到的一些想法是:

  • 将子类实现为服务
  • 创建一个非角度ee静态类或singleton并调用它
  • 重做子类以将其所有对象存储在服务中&在每个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();
}