简体   繁体   中英

Select component instance by directive via @ViewChildren in Angular?

I have multiple components, such as FirstTabComponent , SecondTabComponent , etc...

In the parent component I need to be able to select all component instances.

I tried to use a common directive as a selector, but it only allows me to select either a Directive Instance or a Component Instance...

@Directive({selector: '[tab]'})
export class Tab {}

export interface Tab {
    goNext(): Observable<any>;
}

@Component({...})
export class FirstTabComponent implements Tab {}

@Component({...})
export class SecondTabComponent implements Tab {}

// Wrapper Component Template
<app-first-component tab></app-first-component>
<app-second-component tab></app-second-component>

// Wrapper Component

// This approach selects only 1 component
@ViewChildren(Tab, {read: FirstTabComponent}) tabs: QueryList<Tab>;

// Whereas this one selects directive
@ViewChildren(Tab,) tabs: QueryList<Tab>;

just use a template tag as your selector:

<app-first-component #tab></app-first-component>
<app-second-component #tab></app-second-component>

and then select it like

@ViewChildren('tab') tabs: QueryList<Tab>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM