1

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>

1 Answer 1

1

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();
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.