在* ngFor的所有卡中反映相同的所选数据

时间:2019-02-21 13:19:20

标签: angular angular-material angular7 angular-ngfor

我使用* ngIf创建了多张卡片。
在它里面我有下拉选择(使用垫选择)。当我从下拉菜单中选择一个选项时,选定的选项会反映到所有不需要的卡上。

<div class="allCards">
    <div *ngFor="let card of cardArray; let i=index">
      <mat-card class="example-card">
        <mat-card-header>
          <p class="productOffer">20% OFF</p>
        </mat-card-header>

          <img  mat-card-image src="https://material.angular.io/assets/img/examples/shiba2.jpg"
            alt="Photo of a Shiba Inu">
            <mat-card-subtitle>{{card.name}}</mat-card-subtitle>
        <mat-card-content>

            <del >₹{{card.orgAmt}}</del>
            <p ngDefaultControl >₹{{card.discAmt}} </p>
        </mat-card-content>


        <mat-card-actions>

          <div class="actionItems">
            <mat-form-field style="width:150px;">
              <mat-select  placeholder="Select Quantity"  [(ngModel)]="selectedValue">
                <mat-option ngDefaultControl  *ngFor="let food of card.foods"  [value]="food.value">
                  {{food.viewValue}}
                </mat-option>
              </mat-select>
            </mat-form-field>

            <span class="add-to-cart">
              <button  mat-mini-fab color="primary" (click)="decrCntr(i)" >-</button>
              <span ngDefaultControl >{{card.counterVar}}</span>
              <button  mat-mini-fab color="secondary" (click)="incrCntr(i)" >+</button>
            </span>
          </div>
          <button mat-button type='submit'(click)="onSubmit(i, selectedValue )">Add to Cart</button>

        </mat-card-actions>
      </mat-card>
    </div>
  </div>

2 个答案:

答案 0 :(得分:0)

[(ngModel)] =“ selectedValue” 中添加索引值,以使其唯一。

[(ngModel)] =“ selectedValue {{i}}”

答案 1 :(得分:0)

这是因为所有选择都具有相同的[(ngModel)]="selectedValue"。您可以尝试这样: [(ngModel)]="selectedValue{{i}}"