在 document.addEventListener() 属性 内部使用时模型在 angular 中没有改变

Model not changing in angular when using inside document.addEventListener() property

我正在尝试更新我的模型名称 this.name 单击 document.getElementById('source-selection').addEventListener。不知道为什么它没有更改,而该函数中的一个简单警报触发。 我也对 ngOnChanges 进行了同样的尝试。

ngOnInit() {
      document.getElementById('source-selection').addEventListener('click', function (evt: any) {
       alert('test');
       this.name = `My Angular Test On Click`;
    });
   }
    ngOnChanges() {
      document.getElementById('source-selection').addEventListener('click', function (evt: any) {
       alert('test');
       this.name = `My Angular Test On Click`;
    });
   }

请找渣男linkhere进行实验

在您的代码中,回调函数中的 'this' 不是组件的实例。它已被更改,因为每个新函数都定义了自己的 'this' 值。

一个解决方案是使用自动绑定 'this' 到函数的箭头函数:

document.getElementById('source-selection').addEventListener('click',  (evt: any) => {
   this.name = `My Angular Test On Click`;
});

在箭头函数中,使用封闭执行上下文的 this 值。更多详情 here.

首先,您在非粗箭头函数中使用了 this。这意味着 this 不是指您的组件,而是指函数。

其次,Angular 提供了广泛的事件侦听器,您为什么要使用 vanillaJS?这是适得其反!

用这个

替换你的 html
<div id="source-selection" (click)="changeName()">...</div>

然后在你的 TS 中添加这个

changeName() { this.name = 'My Angular Test On Click'; }