【问题标题】:How to display an already selected Angular Component mat-chip?如何显示已经选择的 Angular Component mat-chip?
【发布时间】:2019-04-23 08:02:40
【问题描述】:

我想根据“可用”属性显示用户打开对话框时已选择的垫片列表。

这是我的 HTML 模板:

`

  <mat-chip-list formControlName="sizes" #chipList [multiple]="true" [selectable]="true">

      <mat-chip #chipRef
        *ngFor="let gearSize of gearItemForm.controls['sizes'].value"
        [ngClass]=""
        [selected]="gearSize.available"  
        (click)="gearSize.available = !gearSize.available; onSelectedChipSize()"  
        [color]="gearSize.color">{{ sizeEnum[gearSize.size] }}, {{ gearSize.available }}  
      </mat-chip>

    </mat-chip-list>

      <input
        matInput
        formControlName="sizes"
        placeholder="Gear sizes..."
        [matChipInputFor]="chipList"
        style="display: none;"
        class="gear-size-label"
      >

    <mat-error *ngIf="gearItemForm.get('sizes').invalid && gearItemForm.get('sizes').touched">Please select a size</mat-error>

  </mat-form-field>     
`

只要gearSize.availabletruefalse,它不会影响mat-chip 上的[selected] 属性,并且永远不会选择芯片组件。用户总是必须手动更改芯片的颜色。如果available 属性为true,如何显示已选择的mat-chip 列表?

【问题讨论】:

  • 这绝对可以。如果您在 selected 属性中使用 true 或 false,它适用于 material.angular.io 上的示例:stackblitz.com/angular/…
  • 所以,您可以将其传递给计算结果为真或假的函数,而不仅仅是将 selected 作为指令属性吗?我有一个对象,其属性可能会更改,具体取决于您选择的项目。我想知道我的属性绑定是不是错了
  • 至少那段代码没有错。选中状态会根据gearSize.available变化。但是有些事情会阻止模板显示更改(例如OnPush 策略)。
  • 让我在问题中更新我的模板。我认为这与我使用 mat-form-field 的事实有关。问题出在“formControlName=sizes”上,一旦我把它拿出来,它就会按预期工作
  • 当然可以。您必须将控件放在输入中,并且它不会包含添加的芯片列表(您必须以并行方式控制它)。

标签: angular angular-components


【解决方案1】:

我尝试创建一个基本 POC 来验证您的需求。这就是实现的样子。 在组件中,我有一个这样的对象数组:

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

 /**
  * @title Basic chips
  */
 @Component({
    selector: 'chips-overview-example',
    templateUrl: 'chips-overview-example.html',
    styleUrls: ['chips-overview-example.css'],
  })
  export class ChipsOverviewExample {

     gearItem = [{'item': 'gearItem1', value: true},{'item': 'gearItem2', value: 
                 false}];
  }  

然后在html中:

   <mat-chip-list>
      <mat-chip *ngFor="let gearSize of gearItem" [selected]="gearSize.value"></mat-chip>
   </mat-chip-list>  

这似乎工作正常,一个工作的 stackblitz 链接在这里:MatchipImplementation

【讨论】:

  • 我认为问题在于我如何将数组与表单同步。我只是注意到以前我有一个基本的FormControl,然后我把一个数组塞进去。这对我当时正在做的事情很好,但是现在它正在崩溃。我试过了,但它仍然没有用。 this.gearItemForm = this.fb.group({ name: this.fb.control(name, Validators.required), price: this.fb.control(price, Validators.required), sizes: this.fb.array(sizes, this.requireSize()), inStock: this.fb.control(inStock), images: this.fb.array(images) })
猜你喜欢
  • 1970-01-01
  • 2018-04-23
  • 2018-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-01
  • 2021-07-27
相关资源
最近更新 更多