处理结构指令上的resize事件而不会丢失上下文

时间:2018-06-08 01:46:15

标签: angular ionic-framework

我正在创建一个ngIf类似结构指令来处理平台。

*ifPl="'android'

它正在工作,我的意思是,如果我在ios,该元素不在DOM中,否则是。 但我希望继续处理resize事件,想象一下我在浏览器上开发并更改设备(它会改变大小),所以我希望此时添加/删除DOM。

我使用resize处理了Renderer2,如下所示:

Renderer2.listen('window', 'resize', this.onResize)

但是我在onResize函数中丢失了我的上下文,this未定义...我希望在这种情况下保持上下文。

Html用法:

<div *ifPl="'android'">
  ROMAIN
</div>

Directive.ts

@Input('ifPl')
set myIfPl(platform: string) {
  this.platform = platform;
  this._context.$implicit = this._context.ifPlatform = IsThisPlateForm(window, platform);
  console.log(IsThisPlateForm(window, platform))
  this._updateView();
  this.render.listen("window", "resize", this.onResize)
}

private _updateView() {
  if (!this._context.$implicit) {
      this._viewContainer.clear();
  } else {
    this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context);
  }
}

onResize(){ console.log(this) } //this == undefined

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式保持上下文

this.render.listen("window", "resize", this.onResize.bind(this));

// arrow function
this.render.listen("window", "resize", () => this.onResize());

对于第二种方式,如果您需要event参数,则需要将其添加到箭头函数中并将其转换为您的函数。

 this.render.listen("window", "resize", (e) => this.onResize(e));
相关问题