簡體   English   中英

從 Angular 8 中的父組件調用動態子組件中的通用接口方法

[英]Calling a common interface method in dynamic child components from parent component in Angular 8

我需要從 Angular 父組件的動態子組件中實現的接口調用通用方法。 我的父 html 組件將如下所示:

parent.component.html :

<div *ngFor = "let config of childConfigs"> 

    <div *ngIf = " config.type == 'a' ">
        <child-a [config]="config"></child-a>
    </div>
    <div *ngIf = " config.type == 'b' ">
        <child-b [config]="config"></child-b>
    </div>
    .
    .
    <div *ngIf = " config.type == 'n' ">
        <child-n [config]="config"></child-n>
    </div>
</div>
<button (click)="resetComponent()"> Reset</button>

假設有一個接口“ComponentActions”,它包含一個方法 resetComponent() 並且所有子組件都實現了它。 示例子組件結構將是這樣的

child-a.component.ts :

export class ChildAComponent implements ComponentActions {

@Input() config;

resetComponent(){
    // do something
}
}

如何通過從父級單擊按鈕在子組件中調用此方法?

是的,這是一個棘手的問題。 您的子組件都繼承了一個基本接口。 有一種方法可以實現這一點。 但是,您將需要調整所有組件類型並將接口更改為抽象類。 別擔心,如果它是一個沒有定義邏輯的抽象類,它會像一個接口一樣,你可以使用implements ,但這樣你就不需要創建一個InjectionToken

export abstract class ComponentActions {
  resetComponent(): void;
}

如果您不能或不想將其設為接口,請執行以下操作:

export const ComponentActionsToken = new InjectionToken<ComponentActions>('component actions');

有了這個,您可以為所有子組件提供以下內容,因此對於您將每個子組件作為useExisting的相應子類:

@Component({
  selector: 'child-x',
  providers: [{ provide: ComponentActions, useExisting: ChildXComponent }]
})
export class ChildXComponent implements ComponentActions {
  resetComponent(): void {
    // do something
  }
}

@Component({
  selector: 'child-y',
  providers: [{ provide: ComponentActions, useExisting: ChildYComponent }]
})
export class ChildYComponent implements ComponentActions {
  resetComponent(): void {
    // do something
  }
}

如果使用注入令牌,則必須將提供屬性中的ComponentActions值更改為ComponentActionsToken

現在感覺就像,根據您的模板,您可以在父模板中擁有ComponentActions多個實例。 因此,您需要一些邏輯來確定要對其執行操作的對象。 但我想你已經做到了。

除此之外,看起來您還想同時對所有組件執行此操作。 所以這就是ViewChildren裝飾器出現的地方:

@Component({
  selector: 'parent'
})
export class ParentComponent {
  @ViewChildren(ComponentActions)
  children?: QueryList<ComponentActions>

  resetComponent(): void {
    this.children?.forEach((child) => child.resetComponent());
  }
}

如果使用注入令牌,則必須將ViewChildrenComponentActions值更改為ComponentActionsToken

就這樣。 不過請注意,這是一個未經測試的代碼,但它應該可以工作。 如果沒有,請告訴我

暫無
暫無

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

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