8000 Improve template null check for used signals in templates · Issue #56303 · angular/angular · GitHub
[go: up one dir, main page]

Skip to content
Improve template null check for used signals in templates #56303
Closed as not planned
@styriandev

Description

@styriandev

Which @angular/* package(s) are relevant/related to the feature request?

core

Description

When using a signal in the template, it would be beneficial if the null check is considered for the accessor, reducing the need for repetitive null checks when accessing properties of the object.

Use Case:
Consider the following scenario in an Angular component where a Person object is accessed:

import { Component, signal } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

interface Person {
  name: string;
}
@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <h1>Hello from {{ name }}!</h1>
    <div>
      @if(person()) {
        {{ person().name }}
      }
    </div>
  `,
})
export class App {
  name = 'Angular';
  person = signal<null | Person>(null);


}

bootstrapApplication(App);

Right now the @if expression already checks if the person is defined. Therefore I would expect that the person().name expression just works but it is still considered as possibly null. Of course, you could handle this using an @if (person() as personDefined) expression but there are some use cases where it would be easier to just check before if a variable is defined and then access the variable.

The error is the following:
image

Example URL: https://stackblitz.com/edit/stackblitz-starters-zs2wwy?file=src%2Fmain.ts

Proposed solution

If a signal is checked against null it is not considered as potentially null inside the if statement.

Alternatives considered

Probably a structural let directive or something like that would also help in this matter. But in the end a typesafe check should already be enough.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0