Reputation: 1111
I am using Angular 2 beta and Typescript ("gulp-typescript": "~2.12.1",
).
I am writing a component for <div qz-badge num-stars="3" class="qz-badge"></div>
import {Component, Input, ElementRef} from 'angular2/core';
import {CORE_DIRECTIVES} from 'angular2/common';
@Component({
selector: '[qz-badge]',
directives: [CORE_DIRECTIVES],
template: `
<div class="stars">
</div>
`
})
export class Badge {
@Input('num-stars') numStars: number;
constructor() {
console.log(new Array(3));
}
ngOnInit() {
let num = this.numStars;
console.log(num);
console.log('--------');
this.stars = new Array(num);
console.log(this.stars);
console.log(this.stars.length);
num = 3;
console.log('--------');
this.stars = new Array(num);
console.log(this.stars);
console.log(this.stars.length);
}
}
It leads ..
3 -------- ["3"] 1 -------- [] 3
In the specification,
Syntax
[element0, element1, ..., elementN]
new Array(element0, element1[, ...[, elementN]])
new Array(arrayLength)
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
I think the length should be 3. Is that a bug or is there some righteous reasons?
Upvotes: 0
Views: 972
Reputation: 31777
Actually it's not a bug, it's simply as it works. All @Input()
's are passed as strings. As Rob Wormald's states in this issue.
Types in TS are purely a compile-time construct
So you won't have a number at runtime, but a string, even if you specify number
as your Input's type. So you can cast it using parseInt
.
// this.numStars is a string, not a number
let num = parseInt(this.numStars);
And that'll make it work correctly.
Here's a plnkr with your case working.
Edit
I missed something in your code. You're passing the value with no binding (no brackets), so it's not getting evaluated. It's a raw string.
The above answer is still valid, but in your case is much easier by passing the value with binding
[num-stars]="3"
Here's another plnkr without the parseInt but using binding.
Upvotes: 2