【问题标题】:How do I change the text of a button when clicked, in Angular在Angular中单击时如何更改按钮的文本
【发布时间】:2021-09-16 18:54:39
【问题描述】:

我想在this.isDisabled 设置为 false 时更改文本,反之亦然,当单击按钮时。 我也用过this.btn.value,但它给我一个错误。

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);
  }
}

【问题讨论】:

  • 你会想要阅读this。不要使用 Angular 操作 DOM。这完全是反模式。
  • 您正在使用哪个版本的 Angular?

标签: javascript css angular


【解决方案1】:

codeSolutionhttps://stackblitz.com/edit/angular-ivy-or2wqk?file=src%2Fapp%2Fapp.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;
      }
    }

检查这是否适合你

说明

  • 点击按钮 enableDisable() 函数在我们切换的地方被调用 isDisabled 标志
  • 按钮的内容根据 isDisabled 标志有条件地更改
  • 如果 isDisabled 为 true “changeText”,否则将显示“Save”(为此使用 Angular Ngif 指令,您可以参考 https://ultimatecourses.com/blog/angular-ngif-else-then

【讨论】:

  • 是的,它工作得很好。太感谢了。如果有一天你有时间,请告诉我你是怎么做到的?再次感谢兄弟..
  • 欢迎。今天我会用解释来编辑这个解决方案
  • @Anonymous 补充说明
【解决方案2】:

我知道接受的答案有效,但它非常复杂。这要简单得多。

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

【讨论】:

  • 不错,看起来更简单,运行流畅。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-16
  • 2018-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
相关资源
最近更新 更多