Angular的click事件更新变量,而不是javascript的onclick方法



我有以下设置:

app.component.ts

prop:string = 'foo';
test(val){
this.prop = val;
}

app.component.html

{{prop}}
<button (click)="test('bar')">Test</button>
<a href="#" onclick="test('bar'); return false;">Test2</a>

都成功调用test(),并且'prop'变量变为'bar'。我的问题是为什么只有第一个(单击)事件更新视图,而第二个没有?我还尝试使用超时和ChangeDetectorRef detectChanges()方法在test()。

两者之间存在语法差异,因此事件触发导致detectChanges

()是单向事件绑定,它将数据从视图传递到组件。

所以在你的情况下,button触发一个事件,导致detectChanges,而不是<a>标签。

onclick作用域是它所附加的DOM元素。所以点击你应该得到一个错误,因为没有这样的东西在你的<a>标签作为test()函数。您可以自己查看作用域:

<a href="#" onclick="console.log(this)">Test2</a>

用事件监听器代替-<a href="#"(click)="test('bar')">Test2</a>

最新更新