Select dropdown shows blank when NG model is null

999 views Asked by At

I am trying to change the second dropdown to default "Select ... " option when i change anything on first dropdown. But i keep showing me blank space, i think the NG is adding extra Option tag in the beginning and i dont know why.

Here is my HTML

 <div>
    <select (change)="onDropChange($event.target.value)" [(ngModel)]="person.name">
  <option value='default' > Select Name</option>
  <option *ngFor="let item of list"> {{item}} </option>
</select>
</div>

<select [(ngModel)]="person.options">
  <option value='default' [selected]="!person.options"> Select Option</option>
  <option *ngFor="let item of options" value="{{item}}"> {{item}} </option>
</select>

Here is my TS



  person= {
    person: "sam",
    options: 123
  }
  list = ["kenny", "sam", "stan"];
  options = [122,4324,234,123]

  onDropChange(value){
      this.purchaser.options = null
  }

code: https://stackblitz.com/edit/angular-3xo9sv?file=src%2Fapp%2Fapp.component.ts

1

There are 1 answers

1
Daniel Guzman On

It's because you don't have any option with value = null, wich is the value you're assigning to this.person.options.

Option 1

Make your default option to be equal to null:

<select [(ngModel)]="person.options">
  <option [value]="null" [selected]="!person.options"> Select Option</option>
  <option *ngFor="let item of options" value="{{item}}"> {{item}} </option>
</select>

note the [value]="null". Now, there's actually an option that matches with the value you're assigning to it.

Option 2

If you don't want your default option to be equal to null, just make sure that the value you're assigning to this.person.options matches with your default option. In the code you provided it's value='default', so basically you just need to

onDropChange(value){
    this.person.options = 'default';
}

Make sure giving proper types to your object since right now it's declaring it as number so you may have a problem. You may create your type but an easy/quick fix to get rid of this problem is declaring it as any. Again, I suggest to define this better.

export class AppComponent  {
    person:any = {
        name: "sam",
        options: 123
    }
    ...
}