首页 > 解决方案 > 我希望在 Angular2 中显示文本

问题描述

在我的 Angular 2 应用程序中,我想在等待服务器响应时禁用该按钮。这是我的示例代码:

 this.service.insert(url , this.object).subscribe(

        param => {
             I get answer to server
        },  error => {
            I get message error from server.
        }, () => {
            console.log('All Angular' , this);
        });

标签: angular

解决方案


您需要在 Angular 组件中有一个属性: isBtnDisabled: boolean; 将其添加到类的顶部。

然后让我们为您的代码添加一些编辑:

insert(){
    this.isBtnDisabled = true; // you just started the request and want to prevent user from clicking the btn again

    this.service.insert(url , this.object)
        .subscribe(
            param => {
                 // success - you get answer from server
                 // make your app respond to it by showing the message, updating the UI, whatever                 
            },  error => {
                // error - you get error message error from server.
            }, () => {
                // final - will always run
                console.log('All Angular' , this);
                this.isBtnDisabled = false; // make the btn clickable again
            });
}

现在您需要将isBtnDisabled属性连接到模板中的实际按钮 DOM 元素

<button (click)="insert()" [disabled]="isBtnDisabled">Insert</button>

因此,如果isBtnDisabled为真,它将disabled在按钮上设置属性。很不言自明。

这只是顶部的樱桃。使用 CSS 'attribute' 选择器设置禁用按钮的样式。

button[disabled]{
  cursor: not-allowed;
  opacity: 0.5
}

推荐阅读