gpt4 book ai didi

angular - 使用模板中的 Angular 2+ 切换 Bootstrap 单选按钮

转载 作者:行者123 更新时间:2023-12-04 22:44:20 26 4
gpt4 key购买 nike

我正在尝试切换一组带有 Angular 类和属性语句的单选按钮。当我单击按钮时,我可以看到根据需要添加和删除了 active 类,并且还设置了 checked 属性。然而,单选按钮实际上并没有被选中。

<div class="btn-group " data-toggle="buttons">
<label class="btn btn-primary" [ngClass]="{'active': s}">
<input type="radio" name="options" id="option1" autocomplete="off" (click)="s=true" [attr.checked]="s"> Yes
</label>
<label class="btn btn-primary" [ngClass]="{'active': !s}">
<input type="radio" name="options" id="option2" autocomplete="off"(click)="s=false" [attr.checked]="!s"> No
</label>
</div>

Live demo of the problem

使用 Angular 5,bootstrap 4.0.0

编辑:不是重复的,因为我知道还有其他方法可以做到这一点。但我想弄清楚为什么上述方法不起作用。

EDIT2:如果我使用 (click)="doSomething()" 绑定(bind)到一个函数,它就可以工作!但也会导致错误,因为未定义函数。如果我创建该函数,它会再次停止工作。

最佳答案

我有更好的解决方案。您可能会喜欢它的简单性。因为用户实际上要单击单选按钮,所以他们使用 ngmodel 将它传递到字段中,这是您不想要的。

html

<div class="btn-group" role="group" aria-label="View Type">
<button type="button" [class.active]="sortClass" (click)="switch(1)" class="btn btn-secondary">
<span>Grid</span>
</button>
<button type="button" [class.active]="listClass" (click)="switch(2)" class="btn btn-secondary">
<span>List</span>
</button>
</div>

组件.ts

// Create variables
private sortClass: boolean;
private listClass: boolean;

// INITIALIZE TRUE / FALSE for both variables
constructor() {
this.sortClass = false;
this.listClass = true;
}

switch(i) {
if (i === 1) {
this.sortClass = !this.sortClass
this.listClass = !this.listClass
} else {
this.listClass = !this.listClass
this.sortClass = !this.sortClass
}
}

然后你会看到一个是active的,另一个是false的。当您单击时,它们会选择真/假。

关于angular - 使用模板中的 Angular 2+ 切换 Bootstrap 单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48695862/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com