首页 > 解决方案 > 使用复选框获取产品 id 并使用 id 创建一个新数组

问题描述

我是 typescript/angular2+ 的新学生,我正在开发一个网站来练习我的学习。

我已经制作了视图,现在我正在创建更新页面,但我有一些问题要完成。

我的更新页面有 2 个选择和 1 个带有 1 个或多个复选框的表。

在选择中,我使用 (valueChanged) 来获取表中的选择 ID,我使用 o [(ngModel)] 来获取全选

总之,我这样做:通过选择复选框获取选择 id 1 获取 1 个或更多产品的 id 获取选择 2 的 id

当我选择复选框时,它会返回这个数组,但我只需要数组中的 id 就可以将它发送到后端,但它也必须是一个数组,因为我的后端配置为接受一个列表。我正在使用 DTO(数据传输对象)。

[{“id”:2225,“name”:“Joy Price”,“isSelected”:true},{“id”:2226,“name”:“Ronnie Jordan”,“isSelected”:true}]

总之

我需要获取 checkedCategoryList ids 并创建一个新数组以发送到模型中的 idsProducts。

做这个的最好方式是什么?目前我无法在这个问题上取得进展

update.component.html


<app-vo-modal keyTitle="Update" keySubtitle="" >


    <form [formGroup]="form">
        <div class="form-group">
            <label class="required">Choose product</label>
            <app-vo-select [itens]="productItens" (valueChanged)="showValues($event)" formControlName="product"></app-vo-select>
        </div>
    </form>


    <div>
        <tbody>
        <table class="table table-striped text-center">
            <thead>
          <tr>
            <th><input type="checkbox" [(ngModel)]="isMasterSel" name="name" value="h1" (change)="checkUncheckAll()"/>
            </th>
            <th>Id</th>
            <th>Name</th>

          </tr>
        </thead>
        <tbody>
                <tr class="text-center" *ngFor="let prod of showTable; index as i">
                    <td>
                        <input type="checkbox" [(ngModel)]="prod.isSelected" name="name" value="{{prod.id}}" (change)="isAllSelected()"/>
                    </td>
                    <td>{{prod.id}}</td>
                    <td>{{prod.name}}</td>
                </tr>
            </tbody>
    </table>
</div>
    <form [formGroup]="form">
        <div class="form-group">
            <label class="required">Choose product the substitute</label>
            <app-vo-select [itens]="productItens" formControlName="product"></app-vo-select>
        </div>
    </form>
</app-vo-modal>

更新组件.ts

export class UpdateComponent implements OnInit {


    products: UpdateModelComponent[] = [];
    showTable: UpdateModelComponent[] = [];
    productItens: SelectOption[];
    form: FormGroup;
    isMasterSel: boolean;
    categoryList: any;
    checkedCategoryList: any;

    @Output()
    valueChanged: EventEmitter<any> = new EventEmitter<any>();

    @Output()
    dataSave = new EventEmitter<any[]>();


    constructor(
        private service: UpdateService,
        private formBuilder: FormBuilder
        ) {

    this.form = this.formBuilder.group({
        product: []
    });


    showValues(id: number) {
        this.service.childproduct(id).
        subscribe((element: EntityBase<UpdateModelComponent>) => {
            this.showTable = element.content;
        });
    }
 
    ngOnInit() {
       
        this.service.parentProduct().
        subscribe((element: EntityBase<UpdateModelComponent>) => {
            this.products = element.content;
            console.log(this.products);
            this.productItens =  this.products.map(t => ({  id: t.id.toString(), text: t.nome }));
        });

    }

     onModalConfirm() {
        
        const a = new UpdateModelComponent();
        this.service.save(a).subscribe(r => {
        });
    }

    checkUncheckAll() {
            for (let i = 0; i < this.showTable.length; i++) {
              this.showTable[i].isSelected = this.isMasterSel;
            }
              this.getCheckedItemList();
    }

    isAllSelected() {
            this.isMasterSel = this.showTable.every(function(item: any) {
                return item.isSelected === true;
              });
            this.getCheckedItemList();
    }

    getCheckedItemList() {
        this.checkedCategoryList = [];
        for (let i = 0; i < this.showTable.length; i++) {
            if (this.showTable[i].isSelected) {
                this.checkedCategoryList.push(this.showTable[i]);
            }
        }
        this.checkedCategoryList = JSON.stringify(this.checkedCategoryList);
        console.log(this.checkedCategoryList); 

> result : array/object of selected products 
> result : [{"id":2225,"name":"Joy Price", "isSelected":true}, {"id":2226,"name":"Ronnie Jordan", "isSelected":true}]


    }
}

更新.model.ts


export class UpdateModelComponent {

    public id: number;
    public name: string;
    public components: UpdateModelComponent[] = [];
    public isSelected = false;

    public idsProducts: [];
    public currentProduct: number;
    public newProduct: number;
}

更新服务.ts

export class UpdateService {

    PATH = '/server/api/product';

    constructor(protected httpClient: HttpClient) { }

    childproduct(page?: Paging): Observable<EntityBase<UpdateModelComponent>> {

        if (!page) {
            page = new Paging();
        }
        return this.httpClient.get<EntityBase<UpdateModelComponent>>(`${this.PATH}/${paginacao.toString()}`);
    }

    parentProduct(id: number): Observable<EntityBase<UpdateModelComponent>> {
        return this.httpClient.get<EntityBase<UpdateModelComponent>>(`${this.PATH}/v2/${id}`);
    }

    save(components: UpdateModelComponent): Observable<any> {
        return this.httpClient.put<any>(`${this.PATH}`, components);
    }
}

标签: javascriptangulartypescriptfrontend

解决方案


2021 年 9 月 9 日更新

你可以使用设置

例子:-

组件 ts

 uniqueIdsUsingSet: Set<number> = new Set();

  prods = [
    { id: 2225, name: 'Joy Price' },
    { id: 2226, name: 'Jordan Ronnie ' },
    { id: 2227, name: 'Price Jordan' },
    { id: 2228, name: 'Ronnie Joy' },
  ];

 uniqueArryUsingSet(item: HTMLInputElement): void {
  if(item.checked) {
   this.uniqueIdsUsingSet.add(+item.id);
  } else {
   this.uniqueIdsUsingSet.delete(+item.id);
  }
 }

组件 HTML

<ng-container *ngFor="let prod of prods">
  <div>
    <label [for]="prod.id">
      {{prod?.name}}
    </label>
    <input
      [id]="prod.id"
      type="checkbox"
      [value]="prod.id"
      #item
     (change)="uniqueArryUsingSet(item)"
    />
  </div>
</ng-container>

旧答案

在组件 ts 文件中

  uniqueIds: any[] = [];

  prods = [
    { id: 2225, name: 'Joy Price' },
    { id: 2226, name: 'Jordan Ronnie ' },
    { id: 2227, name: 'Price Jordan' },
    { id: 2228, name: 'Ronnie Joy' },
  ];

  makeUniqueArrayItems(item: HTMLInputElement): void {
    const itemIndex = this.uniqueIds.indexOf(item.id);
    !item.checked
      ? this.uniqueIds.splice(itemIndex, 1)
      : this.uniqueIds.push(item.id);

    this.uniqueIds = [...new Set(this.uniqueIds)];
  }

在组件 HTML 中

<ng-container *ngFor="let prod of prods">
  <div>
    <label [for]="prod.id">
      {{prod?.name}}
    </label>
    <input
      [id]="prod.id"
      type="checkbox"
      [value]="prod.id"
      #c
      (change)="makeUniqueArrayItems(c)"
    />
  </div>
</ng-container>


<div *ngIf="uniqueIds?.length">
  <h3>
    values
  </h3>
{{uniqueIds}}

</div>

stackblitz 上的示例https://stackblitz.com/edit/angular-uniqu-select-arr?file=src/app/app.component.html


推荐阅读