双向绑定不会使用Date对象更新属性

时间:2019-07-02 08:07:02

标签: angular typescript

我有一个自定义的双向绑定(js日期对象)来连接智能/哑巴组件。我在子级中获取了日期对象,并将更新后的对象发送回父级,但是它没有正确地更新属性。是因为这是一个循环引用吗?

我已经将双向绑定分为属性绑定和事件绑定。事件绑定触发,我运行了将parent属性设置为child事件的方法,但是在视图中不会插入字符串。

如果我创建一个新的Date(),它将起作用;并将日期对象传递到其中,然后将属性设置为新日期。

// Parent Component
@Component({
  selector: 'parent',
  templateUrl: '<child [(time)]="time"></child'
})

export class ParentComponent  {

  public time: Date = new Date();

  // I need this method to to update the time property
  public timeEvent(e: Date): void {
    this.time = new Date(e);
  }

}

// Child Component
@Component({
  selector: 'child',
  templateUrl: './.component.html'
})

export class ChildComponent {

  @Input() private time: Date;
  @Output() private timeChange: EventEmitter<Date> = new EventEmitter<Date>();

  private hour: number;
  private minute: number;

  public timeHandler(): void {
    // Handles logic and validating from input
  }

  // fires when user has selected time from picker and clicked "OK"
  public onAccept(): void {
    this.time.setHours(this.hour);
    this.time.setMinutes(this.minute);
    this.timeChange.emit(this.time);
  }
}

我希望父级中的time属性将从事件中更新,并由子级发出。该属性似乎已更新,但是视图没有更新,直到我将时间设置为一个新的日期对象,该对象是从我从孩子那里得到的日期创建的。

1 个答案:

答案 0 :(得分:0)

您必须更改Date对象。

public onAccept(): void {
  // add this line
  this.time = new Date(this.time.getTime());

  this.time.setHours(this.hour);
  this.time.setMinutes(this.minute);
  this.timeChange.emit(this.time);
}
相关问题