Home > Software engineering >  Select default option on null angular
Select default option on null angular

Time:11-26

I have this dropdown select is working

 <select name="name" [(ngModel)]="name">
 <option value="ACTIVE" [selected]="name.status=='ACTIVE' || name.status==null">Active</option>
 <option value="INACTIVE" [selected]="name.status=='INACTIVE'">Inactive</option>
</select>

but i want if name.status is null then by default select ACTIVE.

This is not working.

Any Solution Thanks

CodePudding user response:

Using ngModel and selected aren't supposed to be used together. In fact the selection selects whatever fits the options value compared to ngModels value.

Hence the right way would be:

<select [(ngModel)]="name.status">
  <option value="ACTIVE">Active</option>
  <option value="INACTIVE">Inactive</option>
</select>

This snippet only doesn't handle the case, that default is null. I recommend to patch the field on init.

Such a patch could look like:

name: NameType;
@Input()
set rawName(value: NameType) {
  this.name = {
    ...value,
    status: value.status || 'ACTIVE';
  }
}

CodePudding user response:

Default select will work on behalf of your NgModule variable value .So you have to mange inside .ts . if null value then assign active to your name.status

  • Related