tymspy tymspy - 11 months ago 38
AngularJS Question

How do you change an angular property inside a html event handler without using a directive?

I'm working on Angular 2 based application. I want to know whether we can set a angular variable inside a HTML Event Handler, is there any possible way?
The below example is just to give an idea about the problem.

<img [class.hidden]="!loaded" src="{{imageUrl}}"
onload="{{loadComplete}}=true;" />

<img *ngIf="!loaded" src="images.gif" />

Error Code:

browser_adapter.js:77 EXCEPTION: Error: Uncaught (in promise): Template parse errors:
Can't bind to 'onload' since it isn't a known native property ([class.hidden]="!loaded" src="{{imageUrl}}"
[ERROR ->]onload="{{loaded}}=true;" />

<img [class.hidden]="!loaded" src="{{imageUrl}}" 
    (load)="loadComplete=true" />

(eventName)="eventHandler" is for subscribing to events in Angular2.
onload is the JavaScript event handler for the load event. For Angular2 you subscribe to the event by omitting the on and use just the plain event name.


You should be aware that if the expression results to false this causes preventDefault to be called on the event

<img [class.hidden]="!loaded" src="{{imageUrl}}" 
    (load)="loadComplete=false" />

To work around ;true can be added so the entire expression result is true

<img [class.hidden]="!loaded" src="{{imageUrl}}" 
    (load)="loadComplete=false;true" />