import { Component, signal } from '@angular/core'; @Component({ selector: 'app-counter', standalone: true, template: `<button (click)="increment()">Count: {{ count() }}</button>` }) export class CounterComponent { count = signal(0); increment() { this.count.update(c => c + 1); } }
The count signal starts at 0. The template shows count() which reads the current value. Clicking the button calls increment() which updates the signal by adding 1. This causes the displayed number to increase.
Signals work perfectly in standalone components.
inject() function in Angular 17 standalone components. Which import statement is correct?The inject() function is exported from @angular/core. Other packages do not export it.
import { Component } from '@angular/core'; @Component({ selector: 'app-sample', standalone: true, template: `<p>Hello World</p>` }) export class SampleComponent { } @NgModule({ declarations: [SampleComponent], imports: [], exports: [SampleComponent] }) export class SampleModule {}
Standalone components are designed to be used without NgModules. Declaring them in an NgModule's declarations array causes a compile-time error.
Exporting a standalone component from an NgModule allows other modules that import this NgModule to use that component without declaring it themselves.
import { Component, signal } from '@angular/core'; @Component({ selector: 'app-msg', standalone: true, template: `{{ message() }}` }) export class MsgComponent { message = signal('start'); constructor() { this.message.update(msg => msg + '->first'); this.message.set('reset'); this.message.update(msg => msg + '->second'); } }
The signal starts as 'start'. The first update appends '->first' making it 'start->first'. Then set replaces the value with 'reset'. The last update appends '->second' to 'reset', resulting in 'reset->second'.