[Fixed] Usinge @Input to increment count of parent component

Issue

I’m doing a simple exercise to demonstrate Child/Parent interaction of variables in Angular. I have looked for solutions online but mostly have been suggesting Observables, Services, and Event Emitters. These however don’t help with the scope of what I’m doing and I want to achieve a simple increment of a child component. Here’s what I have:

import { Component, Input } from "@angular/core";

@Component({
  selector: "counter",
  template: `
    <h2>
      <p>{{ count }}</p>
      <counter-button></counter-button>
    </h2>
  `,
  styles: [
    `
      .counter-button {
        font-size: 1rem;
        padding: 5px 10px;
        color: #585858;
      }
    `
  ]
})
export class CounterComponent {
  count: number = 42;
}

@Component({
  selector: "counter-button",
  template: `
    <button (click)="increment()">
      Click
    </button>
  `
})
export class CounterButtonComponent {
  @Input() count: number;

  constructor() {}

  increment() {
    this.count++;
  }
}

My task here is to have CounterButtonComponent increment the value count in CounterComponent after invoking the function increment() via a button click. I tried passing on the component via constructor but the value was not being assigned back to the main count. How can I use @Input to send the count to the child component and have it increment the parent count? Without using services, emitters, observables.. etc..

Thank you

Solution

Add an eventlistener on the button in the counter component.

import { Component, OnInit} from "@angular/core";

@Component({
  selector: "counter",
  template: `
    <h2>
      <p>{{ count }}</p>
      <counter-button></counter-button>
    </h2>
  `,
  styles: [
    `
      .counter-button {
        font-size: 1rem;
        padding: 5px 10px;
        color: #585858;
      }
    `
  ]
})
export class CounterComponent implements OnInit {
  count: number = 42;
  ngOnInit() {
  document
  .querySelector("#increment")
  .addEventListener("click", () => this.increment());
  }
  increment() {
    this.count++;
  }
}

@Component({
  selector: "counter-button",
  template: `
    <button id="increment">
      Click
    </button>
  `
})
export class CounterButtonComponent {

  constructor() {}
}

I created a stackblitz where everything should work as you want.

Leave a Reply

(*) Required, Your email will not be published