在属性绑定上无限期调用函数

Paw*_*rek 5 typescript angular

我在我的 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

模板定义如下

<html>
    <body>
        <button type="button" [disabled]="buttonShouldBeDisabled">Button</button>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

现在,在我的浏览器控制台中,我可以看到该字符串“属性调用”正在无限期地记录。 不定财产调用

什么可能导致这种行为?我是否理解正确,这意味着我的属性被一遍又一遍地调用,并且可能导致浏览器不响应用户操作?

小智 1

你的整体方法很好,我会这样修改

export class ExampleComponent{
isValid: boolean;

buttonShouldBeDisabled(){
    console.log("property call");
   return this.isValid;}}
Run Code Online (Sandbox Code Playgroud)

将您的 html 元素绑定到 isValid

<button [disabled]="!buttonShouldBeDisabled>Button</button>
Run Code Online (Sandbox Code Playgroud)

现在,您可以简单地设置布尔值,例如单击另一个按钮即可切换“禁用”希望这有帮助,来自柏林的问候。