我在Angular应用程序中发现了一个非常奇怪的问题.
假设我有一个简单的example.component.ts
@Component({
moduleId: module.id.toString(),
selector: 'example',
templateUrl: 'example.component.html',
styles: [``]
})
export class ExampleComponent{
get buttonShouldBeDisabled(){
console.log("property call");
return true;
}
}
模板定义如下
<html>
<body>
<button type="button" [disabled]="buttonShouldBeDisabled">Button</button>
</body>
</html>
现在在我的浏览器控制台中我可以看到,字符串“属性调用”被无限期地记录.
什么可能导致这种行为?我是否理解正确,这意味着我的财产被一遍又一遍地调用,这可能导致浏览器无法响应用户操作?
最佳答案 你的整体方法很好,我会像这样修改它
export class ExampleComponent{
isValid: boolean;
buttonShouldBeDisabled(){
console.log("property call");
return this.isValid;}}
将您的html元素绑定到isValid
<button [disabled]="!buttonShouldBeDisabled>Button</button>
现在你可以简单地设置布尔值,例如点击另一个按钮来切换’禁用’
希望这会有所帮助,柏林的问候.