javascript - How do expose angular 2 methods publicly? -
i working on porting backbone project angular 2 project (obviously lot of changes), , 1 of project requirements requires methods accessible publicly.
a quick example:
component
@component({...}) class mytest { private text:string = ''; public settext(text:string) { this.text = text; } } obviously, have <button (click)="settext('hello world')>click me!</button>, , want well. however, i'd able access publicly.
like this
<button onclick="angular.mytest.settext('hello outside angular!')"></click> or this
// in js console angular.mytest.settext('hello outside angular!'); either way, method publicly exposed can called outside angular 2 app.
this we've done in backbone, guess google foo isn't strong enough find solution using angular.
we prefer expose methods , have list of public apis, if have tips doing well, it'd added bonus. (i have ideas, others welcomed.)
just make component register in global map , can access there.
use either constructor or ngoninit() or of other lifecycle hooks register component , ngondestroy() unregister it.
when call angular methods outside angular, angular doesn't recognize model change. angulars ngzone for. reference angular zone inject constructor
constructor(zone:ngzone) { } you can either make zone available in global object or execute code inside component within zone.
for example
calledfromoutside(newvalue:string) { this.zone.run(() => { this.value = newvalue; }); } or use global zone reference like
zone.run(() => { component.calledfromoutside(newvalue); }); https://plnkr.co/edit/6gv2mbt4yzuhvufv5u1b?p=preview
in browser console have switch <topframe> plunkerpreviewtarget.... because plunker executes code in iframe. run
window.angularcomponentref.zone.run(() => {window.angularcomponentref.component.callfromoutside('1');}) or
window.angularcomponentref.zone.run(() => {window.angularcomponentref.componentfn('2');})
Comments
Post a Comment