angular - 切换开关更改标签文本并返回布尔值 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;
}
}
解决方案
您可以创建开关切换组件并将其导入您的 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}
推荐阅读
- arrays - bash:具有两个数组参数的函数?如何调用以及如何解析?
- python - 从 meshgrid 生成的子数组构建 3D 数组并引入第 3 维
- r - R:如何在 dplyr 中进行条件计数?
- css - 使用 CSS-in-JS 设计 ReactSelect
- php - 在这种情况下,如何从具有不同 where 条件和 differentnet group by 条件的同一张表中进行选择?
- vb.net - 具有值的自定义组合框
- html - 如何方便地填写空白?
- c# - 如何在 WCF 服务中捕获异常?
- ocaml - ocaml中的圆形构建,没有办法解决吗?
- javascript - 如何将用户时区转换为 UTC?