簡體   English   中英

無法訪問傳遞給Angular組件的@Input字段的對象中的公共方法

[英]Can't access public method in an object passed to an Angular component's @Input field

我已經聲明了以下配置器對象。

export class Config {
  constructor(public index: number, public junk: string[] = []) { }
  public count() : number { return this.junk.length; }
}

然后我將它傳遞給我的組件輸入裝飾字段( @Input() config : Config; )。

<div *ngFor="let thing of stuff; let config={index:index,junk:junk};">
  <app-thingy [data]="thing"
              [config]="config">
  </app-thingy>
</div>

當我訪問this.config (檢查它是否已在ngOnChanges()設置)時,我看到我正在設置的值, 我無法訪問該方法。 我還注意到,構造函數中可能包含的任何其他參數或類中可能的公共字段都不會被看到。 基本上,只有HTML標記中明確指定的字段可用。

ngOnChanges(changes: SimpleChanges): void {
  if (changes.config) {
    //console.log((new Config()).count());
    console.log((this.config.count()));
  }
}

注釋掉的行將產生一個錯誤,表示對象上沒有這樣的方法。 第二行證明它是錯誤的 - 對象上有這樣的方法。 我也嘗試使用this.config as Config但這導致了相同的結果。

我感覺到我從HTML標記傳遞的對象並不是所有類型的Config ,因此,它沒有任何我沒有明確指定的方法/變量。 因為我不能只在標記中添加new Config(...) (按照要求和回復),我不知道如何讓愚蠢的計算機相信我它正在處理一個很好的實現課程包括其便利方法。

我該怎么處理呢?

我能想象的最好的方法是構造一個內部Config對象,從傳入的對象中復制字段,然后將HTML插值器綁定到該對象。 然而,我覺得它確實是愚蠢或錯誤(可能兩者)......

我不知道你試圖通過let config={index:index,junk:junk}; 在你的代碼中,這會引發錯誤,至少在我剛剛嘗試它時。 刪除此行並在父級中正確聲明新的Config時,您的代碼應該可以正常工作。

家長:

config = new Config(1,['one','two'])

父html:

<div *ngFor="let thing of stuff">
  <app-thingy [data]="thing" [config]="config"></app-thingy>
</div>

兒童:

ngOnChanges(changes: SimpleChanges): void {
  if (changes.config) {
    //console.log((new Config()).count());
    console.log((this.config.count()));
  }
}

這似乎工作得很好! 演示: https//stackblitz.com/edit/angular-fnmk41? file = app% 2Fapp.component.ts

暫無
暫無

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

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