2016-07-28 5 views
1

У меня есть два компонента - «Дом и счетчик», и я хочу иметь возможность увеличивать переменную шаблона в Counter from Home. Он не работает, кроме инициализации - переменная инициализируется до 17, но после этого приращение не работает.Передача данных из дочернего компонента в шаблон в 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(); 
    } 
} 
Смежные вопросы