Vadim Vadim - 4 months ago 14
AngularJS Question

Angular 2: binding model in window.functionName doesn't work

My current task is to attach external JS widget that from another service to Angular 2 project. This widget requires in params function declared in global scope as callback where it will return data.
My best idea to do it in angular 2 style is to describe function in class(code below).



initWidget(){
window.widgetCallback = function(result){
this.deliveryPoint = result;
};
boxberry.open('widgetCallback', 'some', 'params');
}





This function works properly and deliveryPoint receives needed data but when i calling {{deliveryPoint}} in template, it has no any binding - variable not updating.

How can i fix this problem?

Answer

Hard to tell from your question what the problem is but I assume using ()=> instead of function () fixes your problem:

constructor(private cdRef:ChangeDetectorRef) {}

initWidget(){
  window.widgetCallback = (result) => {
    this.deliveryPoint = result;
    this.cdRef.detectChanges();
  };
  boxberry.open('widgetCallback', 'some', 'params');
}