簡體   English   中英

無法在組件之間傳遞數據

[英]Unable to pass data between components

我們正在嘗試將數組數據從父組件傳遞給子組件,並拋出TypeError: Cannot read property 'setData' of undefined >下面是我們正在嘗試的

父組件

export class RFComponent implements DoCheck {

  finalResult: SModel[];

  @ViewChild(TSFComponent, {static: false})
  private childVar: TSFComponent;

  ........
  click() {
  this.elem = this.getResult(this.prj);
  this.childVar.setData(this.finalResult);
  }

子組件

export class TSFComponent implements DoCheck {

  @Input() setData(e: SModel[]) {
    this.tjlData = e;
  }

我不確定為什么會收到Cannot read property錯誤,因此從父級調用setData()

請重新檢查您的RFComponent 在那里,您會看到this.finalResult沒有在任何地方定義。 您需要將其定義為成員變量,例如

private finalResult: string = 'something'

那么您就可以將其傳遞給其他組件。

但這也不是最佳做法。 據我所知,您沒有正確定義組件。 即使您可以在Angular中使用純類,但通常組件在類聲明中都有裝飾器,您可以在其中定義選擇器,templateUrl和樣式,例如

@Component({
    selector: 'some-selector',
    templateUrl: 'my-template.component.html',
    styleUrls: ['my-style.component.scss']
})

在那里,您可以在模板中引用其他類,然后通過@Input()@Output()參數傳遞數據。

您無需在子級上將setData()定義為Input()。 使用viewchild時,您正在創建對子組件的引用,因此可以訪問其上的方法。 您沒有將setData方法從父級傳遞給子級。

export class TSFComponent implements DoCheck {

  setData(e: SModel[]) {
    this.tjlData = e;
  }

您還需要在view child中引用dom元素。

<child #TSFComponent></child>

@ViewChild('TSFComponent', {static: false}) childVar: TSFComponent;

據我所知,您不需要Input()裝飾器,並且如果刪除它,它應該可以工作。 如前所述,前提條件是TSFComponent實際上是在RFComponent模板內使用的。

您使用@ViewChild錯誤。 您基本上不需要使用setData()函數來“設置”數據。 如果在子組件中使用@Input()裝飾器,則可以設置並在其中聲明變量,並使用從父組件傳遞來的數據。

您可以這樣做:

父組件HTML:

<child-component [parentData]="data"></child-component>

子組件.ts

@Input data: any;

然后,如果要設置與子組件變量/對象相等的變量或對象,則在父組件中引用子組件變量並分配值。 見下文:

子組件對象->父組件對象

給數據對象賦予新值的子組件

someCode() {
    data = {
        someData: "Hi there",
        someMoreData: "Hello there again"
    }

父組件引用和關聯新對象

parentData: any; 

assignData {
    this.childComponent.data = parentData;
}

暫無
暫無

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

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