2

I am trying to change the disabled attribute of the tag on a button click using Angular 2. So far I can disable it once, however I would like to toggle this function back and forth.

This is my code for my HTML template.

<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>

This is my code from my component

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;

}

This is the browser of what I currently have with console.logs to show my property value is changing. Broswer Image

1 Answer 1

1

The right hand side of the [disabled] directive needs to be a boolean value. Both "disabled" and "abled" are truthy values. Thus, it evaluates to [disabled]="true"

Example:

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;

}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for your solution! This has helped a lot!
@EdwardMuldrew Glad I could help :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.