Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct use of Elvis operator in Angular2 for Dart component's view

I see in Angular2 Dart Angular for Dart Cheat Sheet (v2.0.0-beta.2) that the Elvis operator is supported.

I am trying to use it in an a components view but it seems that it is not allowed here.

Given

.html

  <div
    <label
        for = "first">First<span class = "require">*</span></label>
    <input
        type = "text"
        [(ngModel)] = "name?.first"
        id = "first">

.dart

...
Name name = new Name();
...

Running the application gives the following error:

error trace

Transform TemplateCompiler on 
epimss_ng2_reg|lib/components/name_component.ng_meta.json threw error: Template parse errors:
Parser Error: The '?.' operator cannot be used in the assignment at column 13 in [name?.first=$event] in NameComponent@39:12 ("
        <input
            type = "text"
            [ERROR ->][(ngModel)] = "name?.first"
            #firstCtrl = "ngForm"
            [ngFormControl] = "nameForm"): NameComponent@39:12

What circumstance can I use the operator in a component's view?

Cheers

like image 980
st_clair_clarke Avatar asked Feb 02 '16 19:02

st_clair_clarke


People also ask

What is Elvis operator in angular?

The Safe Navigation Operator is also known as the "Elvis Operator". This operator is very useful to protect against null and undefined values in property paths. This operator allows us to navigate an object path in situations when we are not aware whether a path exists or not.

Why was Elvis an operator?

The name "Elvis operator" refers to the fact that when its common notation, ?: , is viewed sideways, it resembles an emoticon of Elvis Presley with his signature hairstyle.


1 Answers

As the error message says it can't be used for assignment. Where should the value be assigned to when name is null? If you split the short form to the more explicit one

[ngModel]="name?.first" (ngModelChange)="name.first=$event"

then you can use the elvis operator.

like image 108
Günter Zöchbauer Avatar answered Oct 05 '22 17:10

Günter Zöchbauer