What is the process for updating button text upon clicking in Angular?

To toggle the text based on whether this.isDisabled is set to false or true, you can implement a function that changes it when the button is clicked. I attempted to use this.btn.value, but encountered 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()">Toggle</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);
  }
}

Answer №1

solutionCode:https://codepen.io/example-angular-code/pen/vZvQGM?file=src%2Fapp%2Fapp.component.html

<button id="changeText" (click)="toggleFunction()">
  <span *ngIf="isEnabled; else message">
    changeText
  </span>
</button>
<ng-template #message>
  Save
</ng-template>

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

give it a try and see if it meets your requirements

Explanation

  • when the button is clicked, the toggleFunction() is executed to switch the value of isEnabled flag
  • the text on the button changes based on the value of isEnabled flag
  • if isEnabled is true, "changeText" is displayed; otherwise, "Save" is displayed (NgIf directive in Angular is used for this purpose, you can learn more about it here)

Answer №2

The solution provided in the response is effective, however, it may be considered overly complex. Here is a simpler approach:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript HashMap implementation with Lists as values

Currently delving into TypeScript, I am attempting to generate a collection in a manner akin to the following Java example: HashMap<String, List<String>> hashMap = new HashMap<String,List<String>>(); Struggling to locate any releva ...

Vue email validation is failing to return a valid email address

I'm relatively new to Vue and have implemented email validation using the reg expression in my Vue script data for this project. By utilizing console.log(this.reg.test(this.email)) and observing the output while users input their email, the validation ...

Reserved space for both double and single quotation marks

I've created a function that generates a table of specified size with predetermined content in each cell, and displays it within a designated div ID. generate_table(4, 4, 'Cell Content', 'display') To test this function, I added a ...

Why is it that when the form is submitted, the value becomes unclear?

This is a form with HTML and TypeScript code that I am working on. <form> <div class="form-group"> <input class="form-control" ([ngModel])="login" placeholder="Login" required> </div> <div class="form-group"> &l ...

What is the best way to transfer an id from JavaScript to Rails while utilizing ajax?

Is there a way to call a rail route and pass in an ID from javascript? I have recently started using rails routes within my application, even in js. The current code I am using is: # app/assets/javascript/verifying_link.js $.ajax({ url: "/verify_link/ ...

Having difficulty retrieving values while using async-await

Utilizing the code below has been successful for me. I managed to retrieve the data in the spread (then), returning a http200 response. Promise.all([ axios({ method: 'post', url: 'https://oauth2.-arch.mand.com/oauth2/token&a ...

Creating Browser Extensions with Vue.js and Vue CLI

I am in the process of creating a Chrome Extension with a frontend powered by Vue.js. Everything was going smoothly using vuecli until my app started utilizing the Webextension-API. This API is only accessible to registered Extensions, not normal websites. ...

What benefits can be gained from utilizing the beforeEach function within Jest testing?

I am currently immersing myself in the world of Jest by following this informative guide. Can you explain the benefits of utilizing the beforeEach function in Jest? I have a particular interest in identifying action dispatches. I believe that two segments ...

instructions on how to showcase a text message within the fontawesome square icon

Can someone help me with styling my code? I want to display a text message inside a square box with dimensions of 1x. <span class="fa-stack fa-5x" style="margin-left:5%"> <i class="fa fa-square-o fa-stack-2x"></i> </span> ...

What is the best way to sequentially invoke methods in Angular?

When initializing in the ngOnInit() method, I need to call several methods synchronously. However, all these methods involve asynchronous calls to an API. The challenge is that certain variables must be set before proceeding with the subsequent methods. Un ...

Displaying Angular reactive form data on screen and then populating it in a jQuery table

Successfully retrieving and displaying data from a template-driven form in Angular, however encountering difficulties when trying to achieve the same with a reactive form. The ultimate goal is to showcase this data on a jQuery table. ...

Interact with USB drive using electron to both read and write data

I am currently developing an electron project that involves copying files from a computer to USB drives. I need the ability to transfer files and folders to the destination USB drive, as well as determine the amount of free space on the drive. I have expe ...

What are the steps to integrate dynamic data into chartjs?

Can you assist me in understanding how to dynamically populate Chartjs with data from a json file? Specifically, I am looking to dynamically fill the labels and data fields. Sample JSON File <<< [ { "EFICAZ_TAB_ITEM_ID":1, " ...

JavaScript personalized video controls. Silence the video by manipulating the input range element

As a newcomer to javascript, I am working on creating custom video controls using js. One issue I am facing is with a span element that contains a mute/unmute icon. When I hover over this span element, a child element appears with an input range bar for ad ...

Is there a way to create a table cell that occupies zero space?

I have a very intricate table setup that resembles a tree structure, with only a few cells on the left and many on the right. I am looking to completely hide specific cells, along with their entire rows, using JavaScript based on their class. Using visibi ...

How to utilize DefinePlugin in Webpack to pass NODE_ENV value

I am attempting to incorporate the NODE_ENV value into my code utilizing webpack through the use of DefinePlugin. I have reviewed a similar inquiry on Stack Overflow, but I am still encountering issues. Here is the configuration I am working with: In pac ...

Creating routes with dynamic components or importing dynamic components in Angular 2 is a versatile and powerful feature

Is there a way to dynamically create routes or import components based on data? For instance, suppose I have a JSON file with objects containing RouteNames, paths, and ComponentNames. How can I dynamically generate route definitions from this data? The ch ...

Concealing HTML pages in Node.js: A step-by-step guide

I have a specific requirement where my website's html pages should only be accessible to users who are logged in. However, when I used the command below, my html pages became public: app.use(express.static('public')); For instance, I do no ...

Managing VueJS components and Observers during the rendering process to ensure smooth functionality in a multi-phase environment

Situation: As part of my development work, I am creating a Vue scroll component that encompasses a variable number of HTML sections. This component dynamically generates vertical page navigation, allowing users to either scroll or jump to specific page lo ...

What is the process of converting the timing from my stopwatch to a standard time format?

I am currently working on a stopwatch project where I log the time into an array. However, when I try to use Math.min(array) or Math.max(array), it returns NaN (not a number). The time format for the stopwatch is like 00:00:15.91 which is not recognized as ...