Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: Parse input/select string value into strong typed value

I'm searching for over a day now to get the right answer, but I'm still a bit clueless. The question is really simple: I have a model with a property which is a boolean. I map that property to a select, which allows the user to select the right value (true, false or null). Angular is actually returning a string. To get concrete:

I have the following component:

@Component({
  selector: 'clientlist',
  templateUrl: './app/components/clientlist/clientlist.html'
})

export class ClientListComponent {  
   searchRequest : ClientSearchRequest;
}

I have the following tempalte:

<select [(ngModel)]="searchRequest.online" class="form-control" (onchange)="search()" numberBinder>
    <option value="">Select</option>
    <option value="true">Online</option>
    <option value="false">Offline</option>
</select>

And the search request model class:

export class ClientSearchRequest {
name: string;
online: boolean;
status: string;
page: number;
pageSize: number;

constructor() {
    this.name = "";
    this.online = null;
    this.status = "";
    this.page = 1;
    this.pageSize = 50;
}

}

When I let the model get filled, the online field is set with a string ("true"). How to fix this? What is the right approach without creating extra components etc.

like image 925
Maarten Kieft Avatar asked Mar 15 '26 20:03

Maarten Kieft


1 Answers

I would try to use the ngValue directive. This way you will be able to use an object instead of a string for values:

<select [(ngModel)]="searchRequest.online" class="form-control" 
        (onchange)="search()" numberBinder>
  <option [ngValue]="'null'">Select</option>
  <option [ngValue]="true">Online</option>
  <option [ngValue]="false">Offline</option>
</select>

Using a null value doesn't work so you need a workaround for this. See this question for more details:

  • Angular2 select with ngValue null
like image 177
Thierry Templier Avatar answered Mar 18 '26 09:03

Thierry Templier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!