Angular2 在不使用 @ViewChild 加载其模板的情况下访问另一个组件方法

Angular2 access another components methods without loading its template with @ViewChild

我正在尝试使用 @ViewChild 访问子组件方法,它可以工作,但我也被迫加载它的模板,我不想这样做,因为这也会强制子组件 OnInit, AfterViewInit 和其他系统函数到 运行。

我希望它们 运行 仅当我在不同的场景中调用此子组件时,但我想在 AppComponent 中按需访问此子组件的自定义方法。

那我该怎么做呢?

这是描述问题的 plunker:http://plnkr.co/edit/FT6GTJ8mmUnyFxJAPbGV

您可以看到调用了仪表板 test() 函数,这就是我 想要的 ,但是,它的 ngOnInit 函数也被初始化了,我 不这样做'不想.

template: <h1>AppComponent</h1><my-dashboard></my-dashboard>

虽然从 AppComponent 模板中删除 <my-dashboard></my-dashboard> 非常明显,但不加载仪表板模板,但随后我收到错误信息,即仪表板本身未定义(如果删除 [=,您可以看到错误12=] and 运行 the plunker again) 尽管我已经通过 import 语句包含了它。

我错过了什么?

编辑------------------------------------ ---------------------------------------------- ----------------------

所以,最后,您必须使用服务来存储可重复使用的 data/functions 才能顺利工作。

不完全确定您为什么需要这个,但您可以尝试使用 Component 作为提供者。虽然我看不出这如何属于 "if it looks stupid, but it works, it ain't stupid" 规则。

import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core';
import { DashboardComponent } from './dashboard.component';

@Component({
    selector: 'my-app',
    template: `
      <h1>AppComponent</h1>
    `,
    providers: [DashboardComponent]
})

export class AppComponent implements OnInit {

    constructor(public dashboardComponent: DashboardComponent){}

    ngOnInit() {
        this.dashboardComponent.test();
    }

}

plnkr

我假设的另一种方法可能是简单地启动一个新的 class 实例,这将导致如下结果:

import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core';
import { DashboardComponent } from './dashboard.component';

@Component({
    selector: 'my-app',
    template: `
      <h1>AppComponent</h1>
    `
})

export class AppComponent implements OnInit {

  public dashboardComponent: DashboardComponent = new DashboardComponent();

    constructor(){}

    ngOnInit() {
        this.dashboardComponent.test();
    }
}

plnkr

但是我还是不明白你为什么要这样做。 显然您的组件中存在不应该存在的逻辑