2016-07-28 88 views
1

我有兩個組件 - Home和Counter,我希望能夠在Counter中從Home中增加模板變量。它不起作用,除了初始化 - 變量初始化爲17,但之後增量不起作用。將數據從子組件傳遞到模板in angular2

CounterComponent

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}} 

HomeComponent

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> 

回答

1

我會使用ViewChild裝飾引用的計數器部件。有了這個實例,你可以用它編程地進行交互。

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

    doSomething() { 
    this.counter.activate(); 
    } 
} 
相關問題