1

コンポーネントへの入力を数値に自動的にキャストする方法はありますか?

たとえば、このコンポーネントは次のように初期化されます。

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

そしてここで定義されています:

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

limit数値または整数に自動的にキャストする方法はありますか?

それ以外の場合は、 is を文字列または任意の in として入力するかTypescript、コンポーネントを in の数値にキャストして開始する必要がありますがngOnInit()、これは避けたいと思います。

4

2 に答える 2

1

http://victorsavkin.com/post/119943127151/angular-2-template-syntax (セクション 定数の受け渡し)によると

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

と同等です (つまり、構文シュガー)

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

つまり、常に文字列バインディングになります。@Sasxaが彼の回答ですでに述べたように、プロパティバインディングを使用して目的のタイプを取得します。

于 2016-02-14T02:12:09.343 に答える
1

プロパティ バインディングを使用する必要があります。

<list-of-playlists [limit]="5"></list-of-playlists>
于 2016-02-14T01:10:40.607 に答える