Goranov
Goranov

Reputation: 395

Pass data from child component to template in angular2

I've got two components - Home and Counter and I want to be able to increment template variable in Counter from Home. It doesn't work, except initialization - the variable is initialized to 17, but after that the increment doesn't work.

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>

Upvotes: 1

Views: 621

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202346

I would reference the counter component using the ViewChild decorator. With this instance, you can interact programmatically with it.

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

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

Upvotes: 1

Related Questions