【问题标题】:Angular Input() takes undefined after providing default valueAngular Input() 提供默认值后未定义
【发布时间】:2019-06-12 18:57:48
【问题描述】:

下面是使用 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 属性,那么组件中的 color 变量应该采用 'red' 作为默认值。

但是当我将其记录为:

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

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

这是上述日志的控制台

8 "English" undefined
6 "Spanish" "blue"

第一个日志是当项目 包含 color 属性时,第二个是当它包含属性 color 且值为 蓝色

【问题讨论】:

    标签: javascript angular angular-input


    【解决方案1】:

    您可以对输入属性使用setter 来确定它是否为有效值并将其分配给默认值

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

    https://stackblitz.com/edit/angular-setter-for-null-input-property 创建的示例

    【讨论】:

    • Typescript 为此抛出 @angular-eslint/no-input-rename 所以它看起来不像是正确的修复。
    【解决方案2】:

    默认值是指当你不传递任何值时,Angular 会放默认值。但是在这里你传递了undefined(当属性不存在时),很明显,角度将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";
      }
    });
    

    未经测试,但应该可以工作!

    【讨论】:

      猜你喜欢
      • 2023-02-02
      • 2018-07-08
      • 1970-01-01
      • 2015-06-15
      • 2020-05-04
      • 1970-01-01
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多