我有两个组件 - Home和Counter,我希望能够在Counter from Home中增加模板变量。它不起作用,除了初始化 - 变量初始化为17,但之后增量不起作用。
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>
答案 0 :(得分:1)
我会使用ViewChild
装饰器来引用计数器组件。通过此实例,您可以使用它以编程方式进行交互。
@Component({
(...)
})
export class HomeComponent {
@ViewChild(CounterComponent)
counter:CounterComponent;
doSomething() {
this.counter.activate();
}
}