下面是与 3 个变量一起使用并为每个变量分配默认值的输入装饰器
@Input() score: number = 0;
@Input() text: string = 'test';
@Input() color: string = 'red';
这就是我在 ngFor 中将值传递给组件的方式。
[text]="item.name"
[score]="item.score"
[color]="item.color"
如果我的项目对象不包含颜色属性,那么组件中的颜色变量应该采用'red'作为默认值。
但是当我将其记录为:
ngOnInit() {
console.log(this.score, this.text, this.color);
}
然后颜色变量将undefined作为值。
这是上述日志的控制台
8 "English" undefined
6 "Spanish" "blue"
第一个日志是当项目不包含color属性时,第二个是当它包含属性color且值为时蓝色
最佳答案
您可以对输入属性使用 setter
来确定它是否是有效值并将其分配给默认值作为
private color: string;
@Input('color')
set Color(color: string) {
this.color = color || 'red';
}
在 https://stackblitz.com/edit/angular-setter-for-null-input-property 创建的示例
关于javascript - Angular Input() 在提供默认值后采用 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56568728/