Optional Chain Operation with Array Indexing in Angular Template

Discussão em 'Angular' iniciado por Galen Howlett, Fevereiro 28, 2025.

  1. In an Angular template I am trying to reference the field of an object in an array. The array is possibly empty, so the object may be undefined. If I try to use an optional chain operation I get a warning. Is there a simple valid way to write this?

    <img #img [src]="images[0]?.url" (error)="setDefaultImage(img)" />


    I get a warning The left side of this optional chain operation does not include 'null' or 'undefined' in its type, therefore the '?.' operator can be replaced with the '.' operator. However, the array is possibly empty so the left side IS possibly undefined, and will break if I remove the optional chain operator. I don't really want to write a getter or ternary operation for something so simple ideally... Is there a TypeScript setting I can modify to suppress this warning? Or a better way to cleanly write this?

    Continue reading...

Compartilhe esta Página