adamdport
adamdport

Reputation: 12633

What's the significance of a dot before brackets in a template, eg name.errors?.['required']

Angular's form validation docs have the following code example:

  <div *ngIf="name.errors?.['required']">
    Name is required.
  </div>

Syntax like name.errors?['required'] I've seen, makes sense.

Syntax like name.errors?.required I've seen, makes sense.

Combining the dot with the bracket name.errors?.['required']" I haven't seen. It doesn't appear to be valid Javascript in Chrome, Uncaught SyntaxError: Unexpected token '['. What's it do?

Upvotes: 0

Views: 37

Answers (1)

adamdport
adamdport

Reputation: 12633

It's just another syntax of Optional Chaining.

Syntax like name.errors?['required'] I've seen, makes sense.

That's actually invalid syntax! It will be evaluated as a ternary (eg a ? b : c, just missing whitespace) and will throw an error requires all 3 expressions at the end of the expression. The correct syntax is with the dot

name.errors?.['required']

https://stackblitz.com/edit/angular-ivy-zjy17n?file=src/app/app.component.html

Upvotes: 1

Related Questions