Angular Input() 在提供默认值后取 undefined

Angular Input() takes undefined after providing default value

下面是与 3 个变量一起使用并为每个变量分配默认值的输入装饰器

  @Input() score: number = 0;
  @Input() text: string = 'test';
  @Input() color: string = 'red';

这就是我将值传递给 ngFor 中的组件的方式。

  [text]="item.name"
  [score]="item.score"
  [color]="item.color"

如果我的 item 对象不包含 color 属性 那么组件中的颜色变量应该取 'red' 作为默认值。

但是当我将其记录为:

ngOnInit() {
    console.log(this.score, this.text, this.color);
  }

那么颜色变量取undefined作为值。

这是

以上日志的控制台
8 "English" undefined
6 "Spanish" "blue"

第一个日志是项目包含颜色属性,第二个是包含属性 颜色 值为 蓝色

默认值是指当你不传递任何值时,angular将使用默认值。但是在这里你传递了 undefined (当 属性 不存在时)并且很明显 angular 将 undefined 作为 color 变量。

您可以通过先将默认值放入数组来解决此问题:

let arr = [
{score:  6, text: "Spanish" color : "blue" },
{score:  8, text: "English" }
]

arr.forEach(function(item, index, theArray) {
  if(theArray[index].color == undefined){
      theArray[index].color = "red";
  }
});

未测试,但应该可以!

你可以对输入属性使用一个setter来判断它是否是一个有效的值,并将它赋给一个默认值如

private color: string;

@Input('color')
set Color(color: string) {
    this.color = color || 'red';
}

https://stackblitz.com/edit/angular-setter-for-null-input-property

创建的示例