Cast inputs to numbers in Angular2?

1.7k Views Asked by At

Is there any way to cast inputs to a component to a number automatically?

For example this component initialised like so:

<list-of-playlists limit="5"></list-of-playlists>

And defined here:

@Component({
    selector: 'list-of-playlists',
    templateUrl: 'list-of-playlists.html'
})
export class MyPlaylistComponent implements OnInit {
    @Input() limit: number;
    ngOnInit() {
        console.log(typeof limit);   // string
    }
}

Is there a way to cast limit to a number or integer automatically?

Otherwise I would have to type is as a string or any in Typescript, or to start the component by casting it to a number in ngOnInit(), which I would like to avoid.

2

There are 2 best solutions below

0
On BEST ANSWER

You need to use Property Binding:

<list-of-playlists [limit]="5"></list-of-playlists>
1
On

According to http://victorsavkin.com/post/119943127151/angular-2-template-syntax (section Passing Constants)

<list-of-playlists limit="5">

is equivalent to (i.e., syntax sugar for)

<list-of-playlists [limit]=" '5' ">

That is, it always results in a string binding. As @Sasxa already mentioned in his answer, use property binding to get the desired type.