Home > Software design >  How do I change the text of a button when clicked, in Angular
How do I change the text of a button when clicked, in Angular

Time:09-16

I want to change the text when this.isDisabled is set to false or vice versa, when the button is clicked. I have also used this.btn.value, but it threw me an error.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
  <div style="display:flex;align-items:center;flex-direction:column;justify-self:center">
    <h2>Welcome to {{name}} </h2>

    <input [disabled]="isDisabled" [id]="myId" type="text" value="Vishwas"> 

    <button id="changeText" (click)="enableDisable()">Edit</button>
  </div>
  `,
  styles: []
})


export class AppComponent {
  name = 'Something';
  public myId = "testId";
  public isDisabled = true;
  public btn = document.getElementById('changeText');
  

  enableDisable(){
    if(this.isDisabled){
      this.isDisabled=false;
      this.btn.textContent="Save";
    }
    else{
      this.isDisabled=true;
      this.btn.textContent="Edit";
    }
    console.log(this.isDisabled);
  }
}

CodePudding user response:

codeSolution:https://stackblitz.com/edit/angular-ivy-or2wqk?file=src/app/app.component.html

<button id="changeText" (click)="enableDisable()">
  <span *ngIf="isDisabled; else prompt">
    changeText
  </span>
</button>
<ng-template #prompt>
  Save
</ng-template>

  import { Component} from '@angular/core';
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      isDisabled: boolean = false;
    
      enableDisable() {
        this.isDisabled = this.isDisabled ? false : true;
      }
    }

check if this works for you

Explanation

  • on click of button enableDisable() function is called where we toggle isDisabled flag
  • content of the button is changed conditionally on isDisabled flag
  • if isDisabled is true "changeText" else "Save" will display (used Angular Ngif directive for this you can refer https://ultimatecourses.com/blog/angular-ngif-else-then)

CodePudding user response:

I know the accepted answer works, but it's very overcomplicated. This is much simpler.

<button (click)="isDisabled = !isDisabled">
    {{ isDisabled ? 'Edit' : 'Save' }}
</button>
export class AppComponent {
    isDisabled: boolean = false;
}
  • Related