When using Angular signal inputs if I want to specify a required input array
import { input } from '@angular/core';
values = input.required<number[]>([]);
I get the build error (StackBlitz)
TS2559: Type 'never[]' has no properties in common with type 'InputOptionsWithoutTransform<number[]>'. [plugin angular-compiler]
What is the correct way to specify a default value?
When an input
signal is set as required
that means that the value will surely be present, else the angular compiler will throw an error and the application will not start. So there is no need to set a default value.
values: InputSignal<number[]> = input.required<number[]>();
The reason you are getting the error because it is expecting the transform
property, where you have provided []
, it should be like:
transform
-> transform the input before sending to the component.
alias
-> another name that can be used to pass the data to the component.
To use these two properties make sure you set the type of the input signal as input.required<number[], number[]>({ ... })
.
import { Component, input, InputSignal } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { JsonPipe } from '@angular/common';
@Component({
selector: 'app-child',
standalone: true,
imports: [JsonPipe],
template: `{{values() | json}}`,
})
export class Child {
values: InputSignal<number[]> = input.required<number[], number[]>({
transform: (innerValues: number[]) => innerValues.map((x: number) => x * 5),
alias: 'valuesProxy',
});
}
@Component({
selector: 'app-root',
imports: [Child],
standalone: true,
template: `<app-child [valuesProxy]="values"/>`,
})
export class App {
values = [1, 2, 3, 4, 5];
}
bootstrapApplication(App);