Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I set a default array value for a required Angular input signal?

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What is the correct way to specify a default value?

>Solution :

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[]>();

Stackblitz Demonstrating the error


The reason you are getting the error because it is expecting the transform property, where you have provided [], it should be like:

  1. transform -> transform the input before sending to the component.

  2. 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);

Stackblitz Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading