我在从异步回调函数切换 Material 设计组件的状态时遇到问题。
HTML 标记
<mat-slide-toggle
class="example-margin"
[color]="color"
[checked]="checked">
</mat-slide-toggle>
不起作用 我确信回调函数会获取它所需的所有内容的上下文,包括“this.checked”变量,但由于某种原因,它不会传播到 Material 设计组件。
checked:boolean;
ngOnInit() {
chrome.storage.local.get('isActive', (data) => {
console.log(data); // {isActive:true}
console.log(this); //context is visible
this.checked = data.isActive; //true
console.log(this.checked); //true
});
}
有效。 这个回调函数工作正常。
checked:boolean;
ngOnInit() {
setTimeout(() => {
this.checked = true;
}, 5000)
}
注意:渲染肯定存在问题。当我单击某个与此完全无关的按钮时,该组件会正确重新渲染。
最佳答案
我认为你可以做的是检查 data.isActive 是否等于“checked”,如果不等于,则切换组件以使它们保持一致。像这样的事情:
ngOnInit() {
chrome.storage.local.get('isActive', (data) => {
if (data.isActive != checked){
this.toggle();
}
});
}
这应该触发一个更改事件,以便将更改传播到 View 。
关于javascript - Chrome 存储 : Unable to change component state from a callback function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614279/