1

I'm currently running into an issue/question about optional chaining in Angular. I'm running Angular 20, with "strictTemplates": true enabled as angularCompilerOptions and "strict": true, as compilerOptions.

@if(component().metadata?.title){
  <span>{{ component().metadata?.title }}</span>
}

In the above example, I have a signal input, which has an interface where metadata is an optional field. If I would delete the ? after metadata inside the span element, it would throw an error: Object is possibly 'undefined'. That feels a bit weird, since the @if statement is around it.

I would expect the below code to run fine, but it isn't.

@if(component().metadata?.title){
  <span>{{ component().metadata.title }}</span>
}

Is this the expected behavior? Or can this be resolved?

1 Answer 1

1

The issue could be caused due to accessing directly via the signal function in multiple places. The types are evaluated across all signal function calls, hence the types are evaluating separately, hence causing typescript issues. Related Github issue below.

signals: TypeScript and nullability #49161

Instead we can leverage @let or @if(<<cond>>; as propName) to narrow the type once and access them across multiple places.


Using @let:

You can also perform type narrowing using @let syntax, if hiding the element is not needed, we can get rid of the @if.

@let metadataTitle = component().metadata?.title;
<span>{{ metadataTitle }}</span>

Using @if(<<cond>>; as propName):

You can use as syntax, do the null check and also use the property inside the if condition.

@if(component()?.metadata?.title; as metadataTitle){
  <span>{{ metadataTitle }}</span>
}

Stackblitz Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.