可能的解决方法如下:
当点击事件触发时,样式变量可能已经更改,但是NG2 Change Detection机制没有检测到变化。我们可以尝试手动触发更改检测以更新样式。
import { Component, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'my-app',
template:
})
export class AppComponent {
public myStyle = {
'font-size': '20px'
};
constructor(private cd:ChangeDetectorRef){ }
onClick() { // Update style this.myStyle['font-size'] = '30px';
// Detect changes
this.cd.detectChanges(); // <---- manually detect changes.
console.log('clicked');
} }
2.使用setTimeOut来解决问题
有时候,在没有触发更改检测的情况下,同步更新会导致一些问题。在这种情况下,您可以尝试使用setTimeout来使异步延迟生效。
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template:
})
export class AppComponent {
public myStyle = {
'font-size': '20px'
};
onClick() { // Update style this.myStyle['font-size'] = '30px';
setTimeout(() => { // <---- asynchronosly update style after 0ms
console.log('clicked');
}, 0);
} }
这两种方法都可以尝试解决点击后不更新样式的问题。