【问题标题】:How to change disabled attribute of input tag on button click using Angular 2如何使用Angular 2更改按钮单击时输入标签的禁用属性
【发布时间】:2017-11-15 07:47:19
【问题描述】:

我正在尝试使用 Angular 2 在单击按钮时更改标签的 disabled 属性。到目前为止,我可以将其禁用一次,但是我想来回切换此功能。

这是我的 HTML 模板代码。

<div *ngIf = "hero">
            <h2> {{hero.name}} details! </h2>
            <button (click)="goBack()">Back </button> 
            <button (click)="edit()"> Edit </button>
            <button (click)="save()">Save </button>
            <div><label> Id: </label> {{hero.id}} </div> 
             <div>
                <label> Name: </label> 
                <input [(ngModel)] = "hero.name" placeholder = "name" 
               [disabled]="change" />
            </div>

        </div>

这是我的组件中的代码

hero: Hero; 
editOn: boolean = true; 
change: string;     
edit(): string

{

if(this.editOn)
{
    this.editOn = false;
    this.change = "abled";
    console.log("Change propery status: ", this.change);
    return this.change;

}else if (!this.editOn)
{
     this.editOn = true; 
    this.change = "disabled";
     console.log("Change propery status: ", this.change);
    return this.change;

}

这是我目前使用 console.logs 的浏览器,用于显示我的属性值正在发生变化。 Broswer Image

【问题讨论】:

    标签: javascript html angular angular2-template


    【解决方案1】:

    [disabled] 指令的右侧必须是 boolean 值。 "disabled""abled" 都是真值。因此,它的计算结果为[disabled]="true"

    例子:

    if(this.editOn)
    {
        this.editOn = false;
        this.change = false;
        console.log("Change propery status: ", this.change);
        return this.change;
    
    }else if (!this.editOn)
    {
        this.editOn = true; 
        this.change = true;
        console.log("Change propery status: ", this.change);
        return this.change;
    
    }
    

    【讨论】:

    • 非常感谢您的解决方案!这帮助很大!
    • @EdwardMuldrew 很高兴我能帮上忙 :-)
    猜你喜欢
    • 2019-12-02
    • 2020-07-28
    • 1970-01-01
    • 2020-01-29
    • 2020-09-03
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 2013-02-24
    相关资源
    最近更新 更多