簡體   English   中英

如何從父組件刷新數據?

[英]How to refresh my data from parent component?

嗨,我想從父組件刷新我的時間戳值。

我的parentComponent.ts

public updateComponent(){
    this.timestamp = new Date();
    this.timestamp.setDate(this.timestamp.getDate() - 30);
    this.timestamp = this.timestamp.toJSON();
}

public ngOnInit() {
  this.updateComponent();
  interval(10000).subscribe(() => {
      console.error('called');
      console.error(this.timestamp);
      this.updateComponent();
  });

}

//my parent.component.html
<app-dashboard-card [refresh]="timestamp"></app-dashboard-card>



//When I catch my data
private ts: any;

@Input()
set refresh(timestamp: any) {
  console.error("TIMESTAMP CHANGE -> ", timestamp);
  this.ts = timestamp;
};

我不知道為什么時間戳更改時我的@Input無法捕獲。

您的代碼似乎僅在使用setInterval()這里工作。

建議:你可以達到同樣不使用二傳位置 ; 只需將時間戳記添加到子組件中,如下所示-

@Input() timestamp: any;

ngOnChanges() {
    console.log("TIMESTAMP CHANGE -> ", this.timestamp);
}

注意:請記住檢查控制台中的日志。

在父組件中更改對象的引用時,將調用ngOnChanges()

  import { Input, SimpleChanges } from "@angular/core";

  ngOnChanges(changes: SimpleChanges) {
    if (changes['refresh']) {
      //do something after value change
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM