how to use angular signals in typescript

There is no such concept as Angular Signals. However, Angular has a powerful event system that is usually used for component interaction. You can use the @Output decorator to define a custom event and signal other components when something happens. Here's an example:

index.ts
import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <button (click)="sendMessage()">Send Message</button>
  `
})
export class ChildComponent {
  @Output() messageEvent = new EventEmitter<string>();

  sendMessage() {
    this.messageEvent.emit('Hello from child');
  }
}
341 chars
16 lines

In the above example, the ChildComponent has a custom event called messageEvent defined using the @Output decorator. It also has a method called sendMessage() that emits the messageEvent event with a payload.

Here is an example of how to subscribe to the event and handle it in ParentComponent:

index.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <app-child (messageEvent)="receiveMessage($event)"></app-child>
    <p>{{ message }}</p>
  `
})
export class ParentComponent {
  message: string;

  receiveMessage($event: string) {
    this.message = $event;
  }
}
316 chars
17 lines

In this example, ParentComponent subscribes to the messageEvent event of the ChildComponent using (messageEvent)="receiveMessage($event)". It also has a method called receiveMessage($event: string) that handles the event payload and updates the message property. Finally, it passes the message property to the template using interpolation {{ message }}.

Hope this helps!

related categories

gistlibby LogSnag