skip to content
Alvin Lucillo

Signal inputs

/ 1 min read

💻 Tech

The example components below use both the traditional @Input decorator and signal inputs. AppComponent passes values to value and value2 props which are used by CounterComponent. Both of the implementation work as expected, but signal inputs are much easier to read. With signal input, you don’t need ngOnChanges anymore. More details from this article.

import { Component } from '@angular/core';
import { CounterComponent } from './counter.component';

@Component({
  selector: 'app-root',
  imports: [CounterComponent],
  standalone: true,
  template: `<counter [value]="counter" [value2]="counter" />
    <button (click)="onIncrement()">
    Increment
</button>`,
})
export class AppComponent {
  counter = 10;
  onIncrement() {
    this.counter++;
  }
}
import {
  Component,
  OnChanges,
  Input,
  SimpleChanges,
  input,
  effect,
} from '@angular/core';

@Component({
  selector: 'counter',
  standalone: true,
  template: ` <h1>Counter value: {{ value }}</h1> <h1>Counter2 value: {{ value2() }}`,
})
export class CounterComponent implements OnChanges {
  @Input()
  value = 0;

  value2 = input(0);

  constructor() {
    effect(() => {
      console.log('new value2: ', this.value2());
    });
  }

  ngOnChanges(changes: SimpleChanges) {
    const change = changes['value'];

    if (change) {
      console.log(`New value: ${change.currentValue}`);
    }
  }
}