在ngFor中动态添加值

时间:2019-01-30 06:05:08

标签: angular typescript angular6 angular-material2 angular2-directives

我想使用ngFor动态添加显示值(在<mat-option>中)。在我的HTML代码中,我在<mat-option>下添加了{{'selected'+ displayValue}},并且在类中定义了“ displayValue”。有人可以帮忙吗? 谢谢。

    <mat-form-field>
    <mat-select placeholder="Favorite food"
   [(ngModel)]="selectedValueModel"
   (ngModelChange)="changedValue($event)" name="food" [compareWith]="compFn">
      <mat-option *ngFor="let selected of SelectedObjectData" [value]="selected">
        {{'selected'+ displayValue}}
      </mat-option>
    </mat-select>
  </mat-form-field>




export class SelectboxComponent {

  displayValue= 'viewValue'

    SelectedObjectData: any[] = [{ value: 'steak-0', viewValue: 'Steak' },
    { value: 'pizza-1', viewValue: 'Pizza' },
    { value: 'tacos-2', viewValue: 'Tacos' }];

  @Input() selectedValueModel = {value: 'tacos-2', viewValue: 'Tacos'};

  @Output() selectedValueModelChange = new EventEmitter()

  changedValue(newValue: any) {
    this.selectedValueModel = newValue
    this.selectedValueModelChange.emit(newValue)
  }

  compFn(c1: any, c2: any): boolean {
    return c1 && c2 ? c1.value === c2.value : c1 === c2;
  }
}

2 个答案:

答案 0 :(得分:1)

您可以在html mat-option中使用它

{{selected[displayValue]}}

在这里检查:https://stackblitz.com/edit/angular-material-with-angular-v5-my8wzh?embed=1&file=app/app.component.html

答案 1 :(得分:0)

我认为您的绑定错误。您的displayValue将始终在视图上显示字符串'viewvalue'。为了显示所选食物和其他选项的显示,您需要使用对绑定的selected对象的访问,并选择要在视图上显示的viewValue字符串属性。

我在下面做了相关的编辑。

component.html:

<mat-form-field>
    <mat-select placeholder="Favorite food"
   [(ngModel)]="selectedValueModel"
   (ngModelChange)="changedValue($event)" name="food" [compareWith]="compFn">
      <mat-option *ngFor="let selected of SelectedObjectData" [value]="selected">
        {{'selected'+ selected.viewValue}}
      </mat-option>
    </mat-select>
  </mat-form-field>

component.ts:

export class SelectboxComponent {

  displayValue= 'viewValue'

    SelectedObjectData: any[] = [{ value: 'steak-0', viewValue: 'Steak' },
    { value: 'pizza-1', viewValue: 'Pizza' },
    { value: 'tacos-2', viewValue: 'Tacos' }];

  @Input() selectedValueModel = {value: 'tacos-2', viewValue: 'Tacos'};

  @Output() selectedValueModelChange = new EventEmitter()

  changedValue(newValue: any) {
    //this.selectedValueModel = newValue
    //this.selectedValueModelChange.emit(newValue)

    // selected value will be reflected here, do what you want with the newValue object
    console.log(newValue)
  }

  compFn(c1: any, c2: any): boolean {
    return c1 && c2 ? c1.value === c2.value : c1 === c2;
  }
}