skip to content
Alvin Lucillo

Angular Signals: computed

/ 1 min read

💻 Tech

computed is used with signals to declare a “computed” variable that has its value updated every time the signal associated to it is updated. The changes are detected because computed is basically subscribed to a signal. With this, you don’t need to monitor or handle events or call a function to update a variable that’s used by the UI template.

In the example below, the image property src is updated every time there are changes to the signal. imagePath, which is bound to the src property, is computed property.

<div>
    <button  (click)="onButtonClick()">
        <span>{{user().name}}</span>
        <img [src]="imagePath()" [alt]="user().name"/>
    </button>
</div>
import { Component, signal } from '@angular/core';

import { generateUser } from '../user_generator';

@Component({
  selector: 'app-user',
  standalone: true,
  imports: [],
  templateUrl: './user.component.html',
  styleUrl: './user.component.css'
})
export class UserComponent {
  user = signal(generateUser()) 
  imagePath = computed(() => 'assets/users/' + this.user().avatar)

  onButtonClick(){
	user = user.set(generateUser());
  }
}