typescript - Angular: การตั้งค่า options ของ mat-select ไม่ปรากฏ แต่ถูกนำไปใช้เมื่อค่าคือ null
ฉันมีตัวเลือกหลายค่าใน Angular และต้องการตั้งค่าบางค่าเริ่มต้น ดูตัวอย่างดังต่อไปนี้: Stackblitz
เทมเพลต
<form [formGroup]="filterFormGroup">
<mat-form-field color="accent">
<mat-label>{{ 'Users' }}</mat-label>
<mat-select formControlName="users" multiple>
<mat-option [value]="null">No User</mat-option>
<mat-option value="user1">User 1</mat-option>
<mat-option value="user2">User 2</mat-option>
<mat-option value="user3">User 3</mat-option>
</mat-select>
</mat-form-field>
</form>
รหัส
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl } from '@angular/forms';
@Component({
selector: 'app-component',
templateUrl: 'app.component.html',
})
export class AppComponent implements OnInit {
filterFormGroup = this.formBuilder.group({
users: [[]],
});
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.filterFormGroup.valueChanges.subscribe(x => console.log('changes: ' + JSON.stringify(x)));
const preselectedFilters = {
users: [null, 'user1']
};
this.filterFormGroup.setValue(preselectedFilters);
}
}
โปรดทราบว่า null เป็นตัวเลือกที่ถูกต้องในตัวอย่างของฉัน ไม่ใช่เพียงตัวแทน ค่าถูกตั้งไว้อย่างถูกต้องแล้ว แต่ตัวเลือก "null" ไม่แสดงว่าถูกเลือก... มีเพียงตัวเลือก "user1" ที่แสดงว่าถูกเลือก
มีใครสามารถอธิบายให้ฉันเข้าใจได้ไหมว่าทำไมมันถึงไม่แสดงว่าเลือกแล้ว และอาจให้วิธีแก้ปัญหาด้วย?
คำตอบ #1
คุณสามารถทำได้โดยการเปลี่ยน null เป็น ''
<mat-option value="">No User</mat-option>
users: ['','user1']
