【问题标题】:@Input() property in angular component returns empty array角度组件中的@Input() 属性返回空数组
【发布时间】:2019-10-15 11:05:26
【问题描述】:

我的日历组件的数据属性装饰为@Input():

import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-calendar',
  templateUrl: './calendar.component.html',
  styleUrls: ['./calendar.component.css']
})
export class CalendarComponent implements OnInit, OnChanges {
  @Input() data: CalendarDay[];

  constructor() {
    this.data = [];
  }

  ngOnInit() {
    this.initDays();
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log(this.data);
    console.log(changes.data);
  }
}

我像这样从另一个组件传入数据:

<app-calendar [data]="this.calendarData"></app-calendar>

并且传递的数据由日历组件中的*ngFor 渲染(渲染完美,一切正常):

<div *ngFor="let item of data">{{item.date}}</div>

我想先解析这些数据,然后再将其呈现到视图中,每当我尝试在日历组件中使用 console.log 数据属性时,我得到一个奇怪的数组,它显示为空,我可以从浏览器控制台“打开”它:

当我尝试像这样记录值时:

console.log(this.data[0])

console.log(changes.data.currentValue[0])

我得到undefined 值。

【问题讨论】:

  • 您是否尝试过从构造函数中删除初始化?那不需要在那里。您应该避免在构造函数中放置依赖注入以外的任何内容。
  • 请尝试创建minimal reproducible example,我推荐stackblitz.com

标签: javascript angular typescript angular7


【解决方案1】:

从构造函数中删除this.data = [],避免在使用依赖注入时更改任何内容。

对于要在模板中使用的每个 Input(),使用 setget,这是最佳做法。

  private _data: CalendarDay[];

  @Input() set data(data: CalendarDay[]) {
    if(data) {
     this._data = data;
    }
  }

  get data(): CalendarDay[] {
    return this._data;
  }

在您的 HTML 中,您应该将其传递给:

<app-calendar [data]="calendarData"></app-calendar>

在日历组件中你可以使用

<div *ngFor="let item of data">{{item.date}}</div>

【讨论】:

    猜你喜欢
    • 2021-02-16
    • 2020-12-27
    • 2019-12-05
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多