【发布时间】:2020-06-23 16:59:01
【问题描述】:
我有一个组件,我在其中创建了一组按钮。用户应该能够选择多个按钮 - 选择时这些按钮的值被添加到数组中,而取消选择时则从数组中删除。 如果用户选择“全部”按钮,则其他按钮将被取消选择。
我在 stackblitz 上有此代码的运行版本,但完整功能与预期不符。
https://stackblitz.com/edit/angular-ivy-je18ji?file=src%2Fapp%2Fapp.component.html
服务检索使用的模拟数据
{
"name": "mockClass",
"label": "mockLabel",
"attributes": [
{
"name": "Button1"
},
{
"name": "Button2"
},
{
"name": "Button3"
},
{
"name": "Button4"
},
{
"name": "Button5"
},
{
"name": "Button6"
}
]
}
数据服务组件
@Injectable({
providedIn: 'root'
})
export class DataClassService {
getMockDataClass() {
return metadata;
}
}
导出的 const 只是一个简单的字符串
export const SEARCH_BUTTON_GROUP_ALL = 'all';
TS 组件
export class AppComponent implements OnInit {
@Input() dataClassName: string;
lame = "Angular " + VERSION.major;
selectedAttributes = ["all"];
dataClass: DataClass;
searchButtonGroupAttributes: any;
constructor(private dataClassService: DataClassService) {}
ngOnInit() {
this.dataClass = this.dataClassService.getMockDataClass();
this.searchButtonGroupAttributes = this.dataClass.attributes;
}
searchButtonGroupClick(attributeName: string) {
if (this.selectedAttributes.indexOf(CONST.SEARCH_BUTTON_GROUP_ALL) >= 0) {
this.selectedAttributes =
attributeName === CONST.SEARCH_BUTTON_GROUP_ALL ? [] : [attributeName];
} else if (this.selectedAttributes.indexOf(attributeName) >= 0) {
const index = this.selectedAttributes.indexOf(attributeName);
if (index >= 0) {
this.selectedAttributes.splice(index, 1);
}
// debugger;
// this.selectedAttributes = this.selectedAttributes.filter(
// a => a !== attributeName && a !== CONST.SEARCH_BUTTON_GROUP_ALL);
} else {
if (attributeName === CONST.SEARCH_BUTTON_GROUP_ALL) {
this.selectedAttributes = [CONST.SEARCH_BUTTON_GROUP_ALL];
} else {
this.selectedAttributes.push(attributeName);
}
}
}
}
HTML 组件
<hello name="{{ lame }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<div class="btn-toolbar">
<button
type="button"
class="btn btn-outline-info m-1"
(click)="searchButtonGroupClick('all')"
[ngClass]="{active: selectedAttributes.indexOf('all') >= 0}"
>
All
</button>
<div *ngFor="let attribute of searchButtonGroupAttributes">
<button
type="button"
class="btn btn-outline-info m-1"
(click)="searchButtonGroupClick(attribute.name)"
[ngClass]="{active: selectedAttributes.indexOf(attribute.name) >= 0}"
>
{{attribute.name}}
</button>
</div>
</div>
期望的结果是能够取消选择和选择分组中的按钮并存储它们的值。我已经调试了代码,向数组添加和删除值的功能正在运行,但这并没有反映在 dom 中,因为按钮没有被正确取消选择
编辑
错误是在 ngClass 的 html 条件中应该是 [ngClass]="{active: selectedAttributes.indexOf(attribute.name) >= 0}
【问题讨论】:
标签: javascript html css angular typescript