Recommended links:
Last active
January 23, 2018 19:00
-
-
Save ComFreek/fb6d80de444004393214 to your computer and use it in GitHub Desktop.
Angular 2: Force view update from within an SVG click listener
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Component, NgZone} from 'angular2/core'; | |
@Component({ | |
selector: 'your-component', | |
template: ` | |
<object data="my-svg.svg" (load)="initHandlers($event)" type="image/svg+xml">SVG not supported!</object> | |
<br> | |
<output> | |
Attribute 1: {{attribute1}}<br> | |
Attribute 2: {{attribute2}} | |
</output> | |
` | |
}) | |
export class YourComponent { | |
private SVGDoc: any; | |
private attribut2: string; | |
private attribute2: string; | |
// STEP 1: Constructor accepts an NgZone and automatically saves it into the | |
// private variable zone (TypeScript syntax sugar) | |
constructor(private zone: NgZone) {} | |
public initHandlers(event) { | |
let objectElement: HTMLObjectElement = <HTMLObjectElement> event.target; | |
let self = this; | |
let doc = objectElement.contentDocument; | |
this.SVGDoc = doc; | |
let cellTexts = doc.querySelectorAll("g"); | |
for (let i=0; i<cellTexts.length; i++) { | |
cellTexts.item(i).addEventListener("click", function () { | |
self.doSomething(); | |
}); | |
} | |
} | |
private doSomething() { | |
this.zone.runOutsideAngular(() => { | |
// STEP 2: Re-compute internal attributes | |
this.attribute1 = calculate(/* ... */); | |
this.attribute2 = calculate(/* ... */); | |
// STEP 3: Force Angular 2 to update the view! | |
this.zone.run(() => { | |
// Optional line, however, the callback is necessary | |
// So the bare minimum would look like "this.zone.run(() => null);" | |
console.log('Update done!'); | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment