尝试获取 viewValue(文本)而不是 Angular 中的多重选择中的值

问题描述 投票:0回答:1

我可以获得与多重选择相关的值,但希望文本显示所选的程序。角度 14.2

打字稿类

export class AffinityProgramsComponent {
  title = 'Affinity Program Extension Form';
  affinityForm = new FormGroup({
    cid!: new FormControl('', Validators.required),
    affinityprogramid!: new FormControl('', Validators.required),
  })

  selectFormControl = new FormControl<Program | null>(null, Validators.required);

  selectedProgram = '';

  programsList: Program[] = [
    { value: '2', viewValue: 'Merchant card connect' },
    { value: '9', viewValue: 'xx credit card credit reporting' },
    { value: '28', viewValue: 'Legal services' },
    { value: '27', viewValue: 'Hx' },
    { value: '3', viewValue: 'xx' },
    { value: '25', viewValue: 'xxxx Executive Groups' },
    { value: '24', viewValue: 'xx Coverage' },
    { value: '26', viewValue: 'xxforce' },
    { value: '22', viewValue: 'HxxB' }
  ];
}

HTML

<mat-form-field appearance="fill" class="example-additional-selection">
  <mat-label class="example-additional-selection-no-border">Affinity Program</mat-label>
  <mat-select multiple class="example-additional-selection-no-border" matNativeControl required [formControl]="selectFormControl" [(value)]="selectedProgram">
    <mat-option *ngFor="let program of programsList" [value]="program.value" class="example-additional-selection2">
      {{program.viewValue}}
    </mat-option>
  </mat-select>
  <mat-error *ngIf="selectFormControl.hasError('required')">Please choose an program</mat-error>
</mat-form-field>
<div><small class="example-additional-selection-no-border">These are the programs selected: {{selectedProgram}}</small></div>
angular angular-material
1个回答
0
投票

在多重选择的情况下,当您尝试读取所选值时,它将返回一维数组的值。

在上述情况下,它将返回为: [2,29,8].=> 所选值的数组。

但是您想要视图值,那么您可以有以下两个选项。

1.将ViewValue作为[value]传递

<mat-form-field appearance="fill" class="example-additional-selection">
  <mat-label class="example-additional-selection-no-border">Affinity Program</mat-label>
  <mat-select multiple class="example-additional-selection-no-border" matNativeControl required [formControl]="selectFormControl" [(value)]="selectedProgram">
    <mat-option *ngFor="let program of programsList" [value]="program.viewValue" class="example-additional-selection2">
      {{program.viewValue}}
    </mat-option>
  </mat-select>
  <mat-error *ngIf="selectFormControl.hasError('required')">Please choose an program</mat-error>
</mat-form-field>
<div><small class="example-additional-selection-no-border">These are the programs selected: {{selectedProgram}}</small></div>

2.您可以使用选定的值数组从数组中过滤出ViewValue

例如,使用上述场景,您将收到如下值。

在上述情况下,它将返回为: [2,29,8].=> 所选值的数组。

let SelectedValue = [2,29,8];
let SelectedtextValue = [];

SelectedValue.forEach(x => {
    let TextValue = this.programsList.filter(y => y.value == x)[0];
    SelectedtextValue.push(TextValue );
});
console.log("SelectedtextValue" ,SelectedtextValue);
© www.soinside.com 2019 - 2024. All rights reserved.