Angular 2组件函数调用

时间:2017-04-19 06:24:04

标签: angular

我想从组件调用函数。

app.component.html

<div class="side">
<app-menu></app-menu>
</div>
<div class="page">
    <router-outlet></router-outlet>
</div>

app.component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'app works!';

}

如何在功能中调用'<app-menu></app-menu>'?

app-menu(menu.component.ts)

import { Component } from '@angular/core';

@Component({
  ...
})
export class MenuComponent {
  addItem(index: number, heading: string, route: string): void {
  }
    groups: Array<any> = [];
}

1 个答案:

答案 0 :(得分:1)

不确定您要完成的任务。 我的猜测

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  @ViewChild(MenuComponent) menu:MenuComponent;

  title = 'app works!';

  // can't be called before the `ngAfterViewInit()` lifecycle callback.
  foo() {
    this.menu.addItem(1, "heading foo", "some route");
  }
}