model
model
declares a writeable signal that is exposed as an input/output
pair on the containing directive.
The input name is taken either from the class member or from the alias
option.
The output name is generated by taking the input name and appending Change
.
function model<T>(): ModelSignal<T | undefined>;
Initializes a model of type T
with an initial value of undefined
.
Angular will implicitly use undefined
as initial value.
ModelSignal<T | undefined>
function model<T>(initialValue: T, opts?: ModelOptions | undefined): ModelSignal<T>;
Initializes a model of type T
with the given initial value.
T
ModelSignal<T>
function model.required<T>(opts?: ModelOptions | undefined): ModelSignal<T>;
Initializes a required model.
Users of your directive/component need to bind to the input side of the model. If unset, a compile time error will be reported.
ModelSignal<T>
Usage Notes
To use model()
, import the function from @angular/core
.
import {model} from '@angular/core`;
Inside your component, introduce a new class member and initialize
it with a call to model
or model.required
.
@Directive({ ...})export class MyDir { firstName = model<string>(); // ModelSignal<string|undefined> lastName = model.required<string>(); // ModelSignal<string> age = model(0); // ModelSignal<number>}
Inside your component template, you can display the value of a model
by calling the signal.
<span>{{firstName()}}</span>
Updating the model
is equivalent to updating a writable signal.
updateName(newFirstName: string): void { this.firstName.set(newFirstName);}