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

In Angular 17+, how to pass signal<number | undefined> to a child component input signal<number>?

Say I have two parent & child components respectively:

Parent Component:

@Component({
selector: 'app-parent',
template: `<app-child [id]="id()"></app-child>`, // this gives compilation error
standalone: true
})
export class ParentComponent {
  id = signal<number | undefined>;
}

Child component:

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

@Component({
selector: 'app-child',
standalone: true
})
export class ChildComponent {
  id = input.required<number>();
}

Since, child component does not accept undefined value, it gives below error:
Type ‘number | undefined’ is not assignable to type ‘number’.

  1. I tried wrapping the child element in @if (id() !== undefined) {}. But it still gives the same error because it is a signal and hence can give a different value at different point of time.

  2. I tried creating @let variable and tried passing it to child component, but Angular does not allow temporary variables like these to be passed on.

>Solution :

You can leverage the new @let to get the necessary type narrowing

@let myId = id();

if(myId) {
   <app-child [id]="myId"></app-child>
}
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