You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现按钮的True/False循环切换状态?(附Angular现有代码)

Toggle Button State Implementation

To get your button to toggle between true and false states on each click, here's how to fix and update your code:

1. Update the Component Class (myComponent.ts)

First, you need to declare a class property to track the current state, then modify the actualizarEstado method to flip that state every time the button is clicked.

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

@Component({
  selector: 'app-my-component',
  templateUrl: './myComponent.html',
  styleUrls: ['./myComponent.css']
})
export class MyComponent {
  // Initialize the state to false (adjust to true if you want the opposite starting point)
  estado: boolean = false;

  actualizarEstado() {
    // Use the NOT operator (!) to flip the boolean value
    this.estado = !this.estado;
    
    // Optional: Verify the state change in the console
    console.log('Current state:', this.estado);
  }
}

Key Fixes & Improvements:

  • Added the estado property as a class member (you must use this. to access it inside the method).
  • Replaced the invalid assignment with this.estado = !this.estado—this negates the current value, creating the toggle loop you need.

2. Optional: Visualize the State in the Template (myComponent.html)

If you want to show the current state to the user (like changing the button text), you can bind the button's content to the estado property:

<button class="btn btn-outline-primary btn-sm" (click)="actualizarEstado()">
  {{ estado ? 'Save Changes' : 'Editar' }}
</button>

This will switch the button text between "Save Changes" (when estado is true) and "Editar" (when estado is false).

How It Works:

  • Each button click triggers actualizarEstado(), which flips the estado value.
  • The first click sets estado to true, the second to false, and this cycle repeats indefinitely.

内容的提问来源于stack exchange,提问作者Paco Zevallos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:25:23