javascript - Mat-select nezobrazuje vybranú hodnotu


let selectedSpecs = this.editData.element.specifications;

this.spec = this.specForm.get('spec') as FormArray;

if (selectedSpecs.length != 0){
  let selectedAttributeIds = [];
  selectedSpecs.forEach((spec, i) => {
    let attribute;
    attribute = {'id': spec.itemDetailId, 'itemId':this.editData.element.itemId, 'name': spec.name};

    this.spec.push(this.formBuilder.group({
      attribute: attribute,
      attributeSpec: spec.description
    }));

    selectedAttributeIds.push(spec.itemDetailId);

  });

  let attributes = [];
  this.selectedCatAttributes.forEach((tempattribute) => {
    let selected;
    if (selectedAttributeIds.includes(tempattribute.id)) {
      selected = true;
    }else {
      selected = false;
    }
    attributes.push(new Attribute(tempattribute, !selected));
  });

  this.attributeList.next(attributes);


}





<div formArrayName="spec" *ngFor="let spec of specForm.get('spec')['controls']; let i= index">
      <div [formGroupName]="i">
        <mat-card class="addShadow">
          <button style="float: right" mat-icon-button (click)="removeSpec(i)"><mat-icon class="specClear">cancel</mat-icon></button>


          <mat-form-field class="spec">
            <mat-select placeholder="Select Attribute" formControlName="attribute" (selectionChange)="selectedOption($event.value,i)">
              <mat-option *ngFor="let attribute of attributeList | async; let index = index" [value]="attribute.attribute" [disabled]="!attribute.allowed">
                {{attribute.attribute.name}}
              </mat-option>
            </mat-select>
          </mat-form-field>

          <mat-form-field class="spec">
            <input matInput placeholder="Specification" formControlName="attributeSpec">
          </mat-form-field>
        </mat-card>
      </div>
    </div>

Ako môžem zobraziť počiatočné hodnoty v rozbaľovacích zoznamoch. Používam formulárové polia. Skúšal som použiť [value] aj [compareWith], ale nič z toho mi nefungovalo.

Odpoveď č. 1

Skúsil som to toľkokrát a prišiel som na spôsob, ako tento problém vyriešiť. Na vyriešenie problému som použil [compareWith]. Tu je moje riešenie.

Toto je metóda, ktorú som volal v [compareWith].

attributeDisplay(attribute1, attribute2) {
  if (attribute1.id == attribute2.id) {
    return attribute1.name;
  } else {
    return "";
  }
}

Tu je môj HTML.

<mat-form-field class="spec">
  <mat-select
    placeholder="Select Attribute"
    formControlName="attribute"
    (selectionChange)="selectedOption($event.value,i)"
    [compareWith]="attributeDisplay"
  >
    <mat-option
      *ngFor="let attribute of attributeList | async; let index = index"
      [value]="attribute.attribute"
      [disabled]="!attribute.allowed"
    >
      {{attribute.attribute.name}}
    </mat-option>
  </mat-select>
</mat-form-field>

Súvisiace články