angular - 创建分组属性
问题描述
我目前正在开发一个关于 Angular 9 的项目,该项目使用户能够将产品添加到他/她的商店,并且每个产品都具有根据它们所属的类别进行分组的属性。In my template, I have a (change)=$event that gets called whenever an attribute is selected. 我的挑战是,在特定类别下,产品具有某些属性,我希望根据它们的组名对其进行分组。例如,我在“汽车”类别下有一个属性组,看起来像;
安全(组名)
- 安全气囊
- 防抱死系统
- 儿童安全系统
- 等等
**人机界面(另一组)
- 有空调
- 蓝牙
- 无线上网
- 等等
从上述分组中,可以从每个组中选择属性,并且每个选定的属性都被分组在给定的组名下。到目前为止,我的代码(我的组件类)如下所示:
/**
* Attempts to create a group of attributes as selected by the user
* @param string groupname
* @return void
*/
createAttributesFor(groupname,$event){
let value = $event.target.value
if($event.target.checked)
{
if(this.attributesGroup.length)
{
for(let k of this.attributesGroup)
{
if(k.group == groupname)
{
if(!k.options.includes(value))
k.options.push(value)
}else
this.attributesGroup.push({group : groupname, options : [value]})
}
}else
this.attributesGroup.push({group : groupname, options : [value]})
}
console.log(this.attributesGroup)
}
这是我的模板上的内容:
<ng-container *ngSwitchCase="'check'" class="mb-1">
<div *ngIf="f.options" class="mt-1">
<label class="control-label mb-0"><small><b>{{ f.name | uppercase}}</b></small></label>
<div class="col-form-label p-0 mb-0" *ngFor="let o of f.options">
<div class="form-check">
<input id="{{ o }}" class="form-check-input" type="checkbox" value="{{ o }}" [formControlName]="f.name" (change)="createAttributesFor(f.name,$event)">
<label for="{{ o }}" class="control-label mb-0"><small>{{ o | titlecase }}</small></label>
</div>
</div>
</div>
</ng-container>
我的问题是;
当我为特定组(例如Safety)选择一个属性时,分组会正常工作,但是如果我移动到下一个组和后续组,我选择的每个属性都会被分组到一个新组中,无论该组是否已经存在。我无法弄清楚为什么会这样。我得到了截图来创建我想要解释的图像:
我需要你们的帮助。
解决方案
您正在遍历所有组并检查当前组是否正确,因此当您使用“蓝牙”到达那里时,首先它会检查“人机界面”是否==“安全”,它没有,所以它去else,并在数组中创建一个新条目,然后将“人机界面”与“人机界面”进行比较,并将蓝牙添加到现有组中。
您需要使用过滤器获取组:
if($event.target.checked)
{
if(this.attributesGroup.length)
{
const group = this.attributesGroup.find(g => g.group === groupname);
if (group) {
if(!k.options.includes(value))
k.options.push(value)
} else {
this.attributesGroup.push({group : groupname, options : [value]})
}
}else
this.attributesGroup.push({group : groupname, options : [value]})
}
推荐阅读
- php - 如何让用户使用 PHP Sessions 登录 1 年?
- python - 循环字符串以扩展特定字符 Pyhton
- python - 使用 importlib 加载已编译的模块
- c - 如何避免使用 io.popen 从 lua 打开的子进程阻塞 C 线程?
- swift - Alamofire URLRequestConvertible 全局标头
- excel - 电子表格 - 我试图找到两列中前 n 个数字的总和
- python - 如何解决python中的字符串表达式?
- c# - 如何在 Puppeteer Sharp 中实现插件隐身?
- python - 如何从python中的URL读取(.RDS)文件?
- r - dplyr 中的排名函数