首页 > 解决方案 > 切换开关更改标签文本并返回布尔值 Angular 11 引导程序

问题描述

我想以现代方式将我网站上几个拨动开关的状态更改为是或否。

我没有找到现成的解决方案,所以我必须弄清楚如何在 Angular 中正确使用它。

我有 10 个开关,它们必须返回一个单独的布尔值并将其文本分别更改为“是”或“否”。如何在 Angular 中实现这一点?

这是我当前的代码,适用于 1 个开关。(在 Angular 11 中使用引导程序 5)

   <div class="form-check form-switch">
      <input class="form-check-input" type="checkbox" (change)="isTrue()" id="flexSwitchCheckDefault">
      <label *ngIf="isTrue()" class="form-check-label" for="flexSwitchCheckDefault">Yes</label>
      <label *ngIf="isFalse()" class="form-check-label" for="flexSwitchCheckDefault">No</label>
    </div>

.ts

export class SComponent implements OnInit {

  status = true;

  constructor() {
  }

  ngOnInit(): void {
  }

  isTrue() {
    return this.status = !this.status;
  }

  isFalse() {
    return this.status === false;
  }

}

标签: angularswitch-statementlabeltoggle

解决方案


您可以创建开关切换组件并将其导入您的 ShareModule

import { Component, EventEmitter, Input, OnInit, Output, TemplateRef } from "@angular/core";

@Component({
    selector: "switch-toggle",
    templateUrl: "./switch-toggle.component.html",
    styleUrls: ["./switch-toggle.component.scss"]
})
export class SwitchToggleComponent implements OnInit {
  @Input() id?: string;
  @Output() onChange: EventEmitter<any> = new EventEmitter();
  value: boolean;

    constructor() {}

    ngOnInit() {}
  
    setValue(value) {
    this.value = value;
    this.onChange.emit({id: this.id, value: this.value});
    }
}
<label class="switch" [ngClass]="{active: value}">
    <input type="checkbox" [id]="id" (change)="setValue(e.target.checked)">
    <span class="slider round"></span>
</label>

并在您的组件中使用它

<switch-toggle [id]="'test1'" (onChange)="doFunction($event)"></switch-toggle>

每次更改开关时都会获取对象,例如 {id: 'test1', value: true or false}


推荐阅读