簡體   English   中英

角子類成員未定義

[英]Angular subclass member undefined

我有一個包含一些狀態信息的Angular組件。 該組件是另一個組件的子組件,該組件用作繼承的組件類的基類。 這個基類有一個@ViewChild成員,其中包含“狀態”組件。 基類具有getState()方法,該方法用於從ViewChild中獲取內部狀態。 在處理實際的基類組件時,這很好用,但是當它是繼承的類組件時, @ViewChild成員是未定義的。 我已經閱讀了TypeScript和其他OOP語言之間的繼承之間的一些不同尋常的區別,但是它似乎並沒有回答這個問題。 我還看到一些問題報告說,裝飾器屬性(例如@Input@Output@ViewChild )在Angular中未正確繼承,作為一種解決方法,您可以在繼承的類中再次聲明它們,但是我嘗試了此操作,但無法解決此問題。

我將代碼簡化為最簡單的情況來顯示問題:

StateComponent

@Component({
  selector : 'app-state',
  template: `
  <p>Here's the state: {{state}}</p>
  `
})
export class StateComponent {
  state: string = "My state.";
}

BaseComponent

@Component({
  selector : 'app-base',
  template: `
    <div>
      <p>BaseComponent</p>
      <app-state></app-state>
    </div>
    `
})
export class BaseComponent {
  @ViewChild(StateComponent) stateCmp: StateComponent;

  getState(): string {
    return this.stateCmp.state;
  }
}

InheritedComponent

@Component({
  selector : 'app-inherited',
  template: `
    <app-base></app-base>
    <div>
      <p>InheritedComponent</p>
    </div>
  `
})

export class InheritedComponent extends BaseComponent {
  constructor() {
    super();
  }
}

AppComponent

@Component({
  selector: 'app-root',
  template: `
  <app-inherited></app-inherited>
  <button (click)="onClick()">Get state</button>
  <p>{{ theState }}</p>
  `
})
export class AppComponent {
  @ViewChild(InheritedComponent) cmpRef: InheritedComponent;

  theState: string;

  onClick() {
    this.theState = this.cmpRef.getState();
  }
}

在此示例中,單擊“ Get state失敗,因為未定義BaseComponent.stateCmp。 將AppComponent更改為使用BaseComponent可以正常工作,並從子組件獲取狀態。 有沒有辦法做我想在這里做的事情?

這里是一個plunkr表示在AppComponent包含InheritedComponent失敗的情況。

這是一個顯示工作情況的插件 ,其中唯一的區別是AppComponent包含BaseComponent。

好吧,經過更多思考之后,我相信我已經回答了我自己的問題。

InheritedComponent<app-base>BaseComponent另一個實例

InheritedComponent是-A BaseComponent ,但由於它沒有一個StateComponent直接孩子,那么它的cmpState是不確定的。

我在這里真正需要的是一種將基本組件模板包括在繼承組件的模板中的方法,以便它是實際的基本組件本身,而不是其他實例。 看來這是Angular中提出的功能請求: https : //github.com/angular/angular/issues/13766

暫無
暫無

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

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