javascript - 更改检测在 Angular 2 的指令事件输出中不起作用

标签 javascript angular events directive

我使用这个指令。但是,在 setAddress 事件输出中,我的组件中未检测到任何更改。 View 未更新。我不明白。

为了测试,如果我删除 google.maps.event.addListener 以替换为简单的 setTimeout 以调用 invokeEvent。它有效。

@Directive({
  selector: '[googleplace]',
  providers: [NgModel],
  host: {
    '(input)' : 'onInputChange()'
  }
})
export class GoogleplaceDirective  {
  @Output() setAddress: EventEmitter<any> = new EventEmitter();
  modelValue:any;
  autocomplete:any;
  private _el:HTMLElement;


  constructor(el: ElementRef,private model:NgModel) {
    this._el = el.nativeElement;
    this.modelValue = this.model;
    var input = this._el;
    this.autocomplete = new google.maps.places.Autocomplete(input, {});
    google.maps.event.addListener(this.autocomplete, 'place_changed', ()=> {
      var place = this.autocomplete.getPlace();
      this.invokeEvent(place);
    });
  }

  invokeEvent(place:Object) {
    this.setAddress.emit(place);
  }


  onInputChange() {
  }
}

在我的组件 View 中

<input type="text" class="validation-address-input" style="margin-top: 100px;" [value]="form.customerAddress"
               (setAddress)="setCustomStartLocation($event)" googleplace>

在我的组件中

/**
     *
     * @param place
     */
    setCustomStartLocation(place: Object) {
        this.currentStep = 2;
    }

最佳答案

place_changed 的处理程序在 Angular 区域外运行。你需要像这样运行它:

constructor(..., private zone: NgZone) {
  ...
  google.maps.event.addListener(this.autocomplete, 'place_changed', ()=> {
    var place = this.autocomplete.getPlace();
    this.zone.run(() => this.invokeEvent(place)); // run inside angular zone
  });

关于javascript - 更改检测在 Angular 2 的指令事件输出中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44086130/

相关文章:

javascript - 在构造一个集合后让 backbone.js 运行一个函数?

angular - "Unexpected end of JSON input" Angular 5

Javascript Shift+Enter(火狐)

javascript - 我如何在 Chrome 和 IE 中跟踪箭头键?

javascript - 单击按钮更改html文本

通过 Object.create 从原始值继承 JavaScript 对象

JavaScript 自定义 JSON 名称 Childs

angular - 在 Angular 中刷新 owl-carousel

javascript - 使用 jQuery 定义的 onInput 事件创建元素?

angular - ng-select 获取对象作为选定值