As we all know there is no ng-init or something for Angular2. So if we try do do something like:
<div #rr="2+2">
{{rr}}
</div>
We will get runtime error:
Error: There is no directive with "exportAs" set to "2+2"
I was watching one of the Angular2 dev videos on youtube and saw exactly the same construction meant to work. Here is the screenshot:
How is this assignment to user template variable possible?
#rr is not equivalent of ng-init. ng-init is gone and won't be back - you need to explicitly initialize fields in a component's class (equivalent of initalizing scope).
You can use exportAs
property of the @Directive
annotation. It exports the directive to be used in the parent view. From the parent view, you can bind it to a view variable and access it from the parent class using @ViewChild()
.
You can read up more on exportAs here.
Please check the sample demo for implementation of exportAs to here.
Local variables aim to reference either the current DOM element:
<div #elt></div>
or a specific element applied on the element:
<div #elt="someDirective" dir></div>
someDirective
corresponds to the exportAs
value of the directive:
@Directive({
selector: '[dir]',
exportAs: 'someDirective'
})
You can't use them to define something else. This is what the message actually tells...
In order to be able to declare variable within template you can leverage custom structural directive like:
@Directive({
selector: '[ngInit]',
})
export class NgInitDirective {
@Input()
set ngInit(context: any) {
this.context.$implicit = this.context.ngInit = context;
this.vcRef.clear();
this.vcRef.createEmbeddedView(this.templateRef, this.context);
}
context: { $implicit?: any, ngInit?: any } = {};
constructor(private vcRef: ViewContainerRef, private templateRef: TemplateRef<any>) {}
}
After that your code can be written as follows:
<div *ngInit="2+2 as rr">
{{rr}}
</div>
or
<div *ngInit="2+2; let rr">
<span>{{rr}}</span>
</div>
Plunker Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With