1

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 Answers 2

1

You need to use Property Binding:

<list-of-playlists [limit]="5"></list-of-playlists>
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Thank you for the elaboration. It's a good link you provided.

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.