在嵌套的ngFor Angular 6中为活动类添加活动类

问题描述 投票:0回答:2

我想在点击后添加活动类,我在ngFor内部有ngFor问题。当我克隆一个无线电时,活动类被添加到所有行,因为它是相同的名称。此外,现在我只能点击一个收音机,我想点击一行中的一个收音机(我不知道如何使行之间的收音机相互独立)

我想在行之间添加独立的活动类,所以我想从Lorem中选择test1,从Ipsum中选择test2,从dolor中选择test1。现在我只能从所有元素中选择一个收音机。

我的例子https://stackblitz.com/edit/angular-aupnma?file=src%2Fapp%2Fapp.component.ts

angular radio-button ngfor
2个回答
1
投票

你有2个问题:

  • 您的无线电没有每个测试的通用名称(因此总共只能选择一个)
  • 您只保留一个选定的项目,因此您只能将该类应用于一个项目)

修改component.ts以保存所选项目

selectedItems = {};
  selectItem(item, id) {
    this.selectedItems[id] = item;
      }

  isSelectedItem(item, id) {
    return this.selectedItems[id] && this.selectedItems[id] === item;
  };
}

修改模板以向您的无线电添加通用名称并更改对活动类的检查

  <label class="btn btn-outline-secondary"
          *ngFor="let item of test.items"
          (click)="selectItem(item,test.id)"
          [ngClass]="{active: isSelectedItem(item, test.id) }">
          <input
          type="radio"
          name="something_{{test.id}}"/>
          {{item}}
        </label>

Stackblitz demo


3
投票

更新为Ali Shahbaz建议对复选框输入进行分组

您可以在app.component.html中尝试这样的操作

    <div class="row" *ngFor="let test of tests">
      <input type="checkbox"
        id="">
        {{test.name}} 
      <div class="btn-group">
        <label class="btn btn-outline-secondary"
          *ngFor="let item of test.items"
          (click)="selectItem(item,test.id)"
          [ngClass]="{active: isSelectedItem(item) && selectedId==test.id}">
          <input
          type="radio"
          name="something{{test.id}}"/>
          {{item}}
        </label>
      </div>
    </div>

在app.component.ts中

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  tests: any[];
  selectedItem: any;
  selectedId:number;

  constructor() {
    this.tests = [{
      id: 1, name: 'lorem', items: ['test1', 'test2', 'test3']
    },
    {
      id: 2, name: 'ipsum', items: ['test1', 'test2', 'test3']
    },
    {
      id: 3, name: 'dolor', items: ['test1', 'test2', 'test3']
    }]

  }

  selectItem(item,id) {
    this.selectedItem = item;
    this.selectedId=id;
  }

  isSelectedItem(item) {
    return this.selectedItem === item;
  };
}
© www.soinside.com 2019 - 2024. All rights reserved.