首页 > 解决方案 > 创建分组属性

问题描述

我目前正在开发一个关于 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)选择一个属性时,分组会正常工作,但是如果我移动到下一个组和后续组,我选择的每个属性都会被分组到一个新组中,无论该组是否已经存在。我无法弄清楚为什么会这样。我得到了截图来创建我想要解释的图像:

属性及其组的图像

我面临的挑战的控制台日志

我需要你们的帮助。

标签: angulartypescript

解决方案


您正在遍历所有组并检查当前组是否正确,因此当您使用“蓝牙”到达那里时,首先它会检查“人机界面”是否==“安全”,它没有,所以它去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]})
}

推荐阅读