Home > OS >  Default option value for a select in angular 12 using ngModel
Default option value for a select in angular 12 using ngModel

Time:06-01

I have a select with an hardcoded option with ngValue of null and other options being filled with an ngFor. I'd like for the first null option to be selected by default. No matter what I do I always have an empty option selected by default.

I get my model name and data from a parent component that gets its data from the api.

The select component .html:

<select name="typeSelect" [(ngModel)]="model" (ngModelChange)="onSelectChange($event)" 
aria-label="Type select">
    <option [ngValue]="null">Select a type</option>
    <option *ngFor="let type of object.types" [ngValue]="type">{{ type.name }}</option>
</select>

Its .ts:

  @Input() object: ObjectData;
  @Output() outputChosenType: EventEmitter<any> = new EventEmitter<any>();
  @Input() model: string = '';

    onSelectChange(chosenType: any) {
        if(chosenType !== null ){...}
    }

I spare you the other checks and logic in my ts because those are working fine, the only thing not working is having the first option slected.

The model comes from another ngFor with this component.

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>

CodePudding user response:

If you change the default value of model to null it will work.

 @Input() model: string = null;
  • Related