3

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.

1 Answer 1

4

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:

Sign up to request clarification or add additional context in comments.

6 Comments

When I apply this, I recieve the following error: Can't bind to 'ngValue' since it isn't a known native property
Which version of Angular2 do you use?
AH! good question, beta 11, I will upgrade to the current version.
I don't know on which version it was added but in beta14 ng-value was renamed to ngValue. See the changelog: github.com/angular/angular/blob/master/CHANGELOG.md
I took me a while to test it, but the upgrade indeed fixed the first problem in the comments. Its now mapping to a boolean. No I will try to do the null value. Thanks a lot :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.