【问题标题】:Angular4 "change" listener only fires onceAngular4“改变”监听器只触发一次
【发布时间】:2018-05-24 19:09:55
【问题描述】:

我有一个选择下拉列表,我正在根据选择从更改中提取数据。它会在第一次加载时正常触发,但在我重新加载或重定向之前不会再次更改。

    getLogs(){
  document.getElementById("placeSelect").addEventListener('change', (e:any)=>{
    this.placeService.getPlace(e.target.value).subscribe((e:any)=>{        
      this.personService.person(e.data.place.person.id).subscribe((e:any) => {
        this.logs = e.data.person.logs
      })
    })
  })

}

我在组件的“ngOnInit”上调用它,也许这就是问题所在?任何想法都会有所帮助。

【问题讨论】:

  • 忘记事件监听器。在模板中,输入select (change)="onChangeHandler($event)"...>,然后在你的组件中有方法onChangeHandler(event)
  • 看到这个链接会有帮助stackoverflow.com/questions/36150107/…

标签: javascript angular addeventlistener lifecycle


【解决方案1】:

这可能会对你有所帮助。

将此代码添加到 Module.ts 的导入中

import { FormsModule } from '@angular/forms';
imports: [FormsModule]

component.ts 内部

 myModel(e: Event) {
    console.log(e);
  }

在 Component.html 中

   <select (ngModelChange)="myModel($event)" [ngModel]="mymodel">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">2</option>
</select>

【讨论】:

  • 我想我应该澄清一下。我很抱歉。但是选择和显示数据的位置在两个单独的组件上。
【解决方案2】:

感谢所有建议,但我设法解决了问题。最大的障碍是选择位于不同的组件中(我很抱歉没有提及),所以我必须将选择信息导出到我的组件中,以显示信息。

component2.ts

import { userInfo } from '../../component1';

然后设置一个延迟,以便在两个组件完全加载后启动监听。好像在我以前的版本中触发过

ngOnInit() {
if(userInfo.place){
  this.getLogsfromPlace()
}    
setTimeout(()=>{
  this.startupUserInfo = userInfo
  document.getElementById("header").addEventListener('change', (e:any)=>{
  this._placeService.getPlace(userInfo.place).subscribe((e:any)=>{
    this._personService.person(e.data.place.person.id).subscribe((e:any) => {
      this.logs = e.data.person.logs
    })
  })
})  }, 3000);
}

非常感谢!

【讨论】:

    猜你喜欢
    • 2011-09-17
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多