Home > Mobile >  Angular 2 - Safe Navigation operator not working in template property binding
Angular 2 - Safe Navigation operator not working in template property binding

Time:11-28

Ng: 13.3.11
TS: 4.6.4

in the Ng template, the following expression using safe navigator throws an error in IntelliJ Idea

[innerHTML]="foo.bar.baz[v1].foobar[v2]?[v3]?[v4]?[v5]"
error:  Parser Error: Conditional expression... requires all 3 expressions at the end of the expression

while this long expression (which is what the safe navigator expression should result in) works just fine:

[innerHTML]="foo.bar.baz[v1].foobar[v2] && foo.bar.baz[v1].foobar[v2][v3] && foo.bar.baz[v1].foobar[v2][v3][v4] ? foo.bar.baz[v1].foobar[v2][v3][v4][v5] : ''"

what am I doing wrong ?

CodePudding user response:

The optional chaining operator (a.k.a the elvis operator) always looks like this: ?.. So your code is missing a dot after some of the question marks. If you change it to look like the snippet below, it will work as expected:

[innerHtml]="foo.bar.baz[v1].foobar[v2]?.[v3]?.[v4]?.[v5]"

Btw, probably foo.bar.baz[v1] could also return nothing, so to go with a version even safer, you can add an elvis operator also after [v1], like this:

[innerHtml]="foo.bar.baz[v1]?.foobar[v2]?.[v3]?.[v4]?.[v5]"
  • Related