Why is typescript setting my value to a 'undefined' string instead of an undefined?

Viewed 222

I have a select dropdown where I set the first value to a undefined.

But the problem is if I select a dropdown value and then go and select the first value ('All') then my bound variable ends up becoming a string 'undefined' and it actually changes it from a number to a string.

memberParams.membership // is a :number and I don't want it to be converted to a string

and memberTypes is a name/value pair

export interface IMemberType {
   value: number;
   name: string;
}

Why is this and how can I prevent it?

this.memberTypes = [{value: undefined, name: 'All'}, ...response.memberships];
<select class="form-control custom-select w-100" name="memberType" [(ngModel)]="memberParams.membership">
  <option *ngFor="let memberType of memberTypes" [value]="memberType.value">
    {{memberType.name}}
  </option>
</select>

1 Answers

The HTML value property is always either a number or a string. So, there is no way to fix it in the Angular template. However, inside your component you can have a setter and getter which can change the value correctly.

Inside your component:

get membership() {
  return this.memberParams.membership;
}

set membership(value: string | number) { 
  this.memberParams.membership = val === "undefined"? undefined : value;
}

You only need to make one small change in your template, which is to change the [(ngModel)] binding from memberParams.membership to just membership.

Related