0
votes

I am trying to change text value outside of Angular2 context using BrowserDomAdapter it is working fine.

But change value is not reflecting on model/component/directive. I am actually looking for $apply similar kind of functionality in anuglar2. I get to know that we can achieve it by using Zone.js Even it is not working.

following is my code snippet, any help/suggestion is appreciated.

` //app component import {Component} from '@angular/core'; import {DefaultDirective} from './default.directive'; @Component({ selector: 'my-app', templateUrl:"./templates/default.tpl.html", directives: [DefaultDirective] }) export class AppComponent { color:string = "Red.."; }

// default.tpl.html
<div>
    ===>{{color}}
    <input type="text" [(ngModel)]="color" [defaultColor]="color"/>
</div>

import { Directive, ElementRef, Input, NgZone } from '@angular/core';
import {BrowserDomAdapter } from '@angular/platform-browser/src/browser/browser_adapter';
@Directive({
    selector: '[defaultColor]',
})
export class DefaultDirective {
  private el: HTMLElement;
  dom:BrowserDomAdapter;
  constructor(el: ElementRef,public zone:NgZone) {
    this.el = el.nativeElement;
    this.dom = new BrowserDomAdapter();
  }
  ngOnInit() {
    this.zone.runOutsideAngular( ( )=>{
      this.zone.run(()=>{ 
        this.dom.setValue(this.el,"Adding some content fro ngOnInit"); 
         // I am changing value of a text field out side of angular context.
         // Value is updating but model is not reflecting
         //Here i can use @Input/@Output but I would like to change it in out side of angular context.
        });
    });
  }
}

`

1

1 Answers

0
votes

Angular doesn't monitors any DOM changes, not inside Angular components nor outside. You might want to emit an event outside Angular and listen to that event inside Angular to update the model in the event handler.

You can listen to global events by prefixing the event name with window: or document:

@HostListener('window:mytextupdate', ['$event']) 
_onTextUpdate(event) {
  this.text = event.detail;
}