问题描述
我有这种怪异的行为,当我将@Input与字符串一起使用时,我会得到“未定义”,但是如果它是一个数字,则数据似乎会被传递。
custom-progress-bar-component.ts
import { Component,OnInit,Input,ViewChild,ElementRef} from '@angular/core';
@Component({
moduleId: module.id,selector: 'custom-progress-bar',templateUrl: './custom-progress-bar.component.html',styleUrls: ['./custom-progress-bar.component.css']
})
export class CustomProgressBarComponent implements OnInit {
@input() step: string;
@input() stepstring : string;
constructor() { }
ngOnInit() {
console.log("step" + this.step); // 1
console.log("stepstring" + this.stepstring); // undefined
}
}
home.html
<StackLayout>
<custom-progress-bar [step]="1" [stepstring]="toto"></custom-progress-bar>
</StackLayout>
我误会什么?
解决方法
通过使用括号,您告诉Angular您要传递的值需要插值。不能完全确定为什么数字可以工作,可能因为变量不能以数字开头,所以可能需要进行一些隐式处理。
您可以删除括号或将一个明确的字符串传递给插值属性:
<StackLayout>
<custom-progress-bar [step]="1" stepstring="toto"></custom-progress-bar>
</StackLayout>
或带有括号
<StackLayout>
<custom-progress-bar [step]="1" [stepstring]="'toto'"></custom-progress-bar>
</StackLayout>
如果它是原始值,我更喜欢无括号属性,但取决于您。