将数据从子组件传递到angular2中的模板

Pass data from child component to template in angular2

我有两个组件 - Home 和 Counter,我希望能够从 Home 递增 Counter 中的模板变量。它不起作用,除了初始化 - 变量被初始化为 17,但之后增量不起作用。

计数器组件

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

@Component({
  selector: 'counter',
  styleUrls: ['app/counter.component/style.css'],
  templateUrl: 'app/counter.component/counter.component.html'
})
export class CounterComponent {

  public counter: number = 17;  

  activate() {
    this.counter++;
  }

  deactivate() {
    this.counter--;
  }
}

counter.component.html

The counter is: {{counter}}

主页组件

import { Component } from '@angular/core';
import { CounterComponent } from './counter.component/counter.component';

@Component({
  selector: 'home',
  directives: [CounterComponent],
  providers: [CounterComponent],
  templateUrl: 'app/home.component.html'
})
export class HomeComponent {

  constructor(public counter: CounterComponent) {}

  doSomething() {
    this.counter.activate();
  }

}

home.component.html

Home component

<button (click)="doSomething()">Activate</button>


<counter></counter>

我会使用 ViewChild 装饰器引用计数器组件。使用此实例,您可以通过编程方式与其进行交互。

@Component({
  (...)
})
export class HomeComponent {
  @ViewChild(CounterComponent)
  counter:CounterComponent;

  doSomething() {
    this.counter.activate();
  }
}