我有一个硬编码选项,ngValue为null,其他选项用ngFor填充。我希望在默认情况下选择第一个null选项。无论我做什么,我总是默认选中一个空选项。
我从父组件获得模型名和数据,父组件从api获取数据。
选择组件。html:
<select name="typeSelect" [(ngModel)]="model" (ngModelChange)="onSelectChange($event)" class="form-select"
aria-label="Type select">
<option [ngValue]="null">Select a type</option>
<option *ngFor="let type of object.types" [ngValue]="type">{{ type.name }}</option>
</select>
其.ts:
@Input() object: ObjectData;
@Output() outputChosenType: EventEmitter<any> = new EventEmitter<any>();
@Input() model: string = '';
onSelectChange(chosenType: any) {
if(chosenType !== null ){...}
}
我在我的ts中省去了其他检查和逻辑,因为它们工作得很好,唯一不工作的是选择了第一个选项。
这个模型来自另一个ngFor组件。
parent.html:
<app-typeSelect-card *ngFor="let object of allObjects.data ; let i = index" [object]="singleObject"
[model]="i.toString()" (outputChosenType)="onOutput($event)"></app-typeSelect-card>
如果你将model的默认值更改为null,它将工作。
@Input() model: string = null;