简体   繁体   中英

How to dynamically get child components instead of using @ViewChild

Basically instead of doing this:

class Controller implements AfterViewInit{
  @ViewChild(IconComponent)
  iconComponent: IconComponent;

  ngAfterViewInit() {
    iconComponent.save();
  }

}

I would like to get a component like this:

class Controller implements AfterViewInit{

  ngAfterViewInit() {
    const iconComponent = someRef.get(IconComponent); // where to get this component from
    iconComponent.save()
  }

}

How do I achieve this?

I am asking this question because I get the component type in the runtime, not compiletime.

Why don't you create the component with the provided ComponentFactoryResolver ?

By this way you can get its componentRef and manage its instance.

Here is the documentation of the ComponentFactoryResolver and you can find there a good implementation example .

You can have an Injection Token. Even though types would cause you errors (hence typecast to any), this would work:

@ViewChild(YOUR_TOKEN as any)
component: YourAbstractClass;

Or, if you marked them all by some template reference variable:

@ViewChild('some', {read: YOUR_TOKEN})
component: YourAbstractClass;

All components derived from your abstract class should provide this token:

@Component({
    selector: 'your-component',
    templateUrl: './yourComponent.template.html',
    styleUrls: ['./yourComponent.style.less'],
    providers: [
        {
            provide: YOUR_TOKEN,
            useExisting: forwardRef(() => YourComponent ),
        },
    ],
})
export class YourComponent extends YourAbstractClass {

This way you could also inject them all into directives.

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