1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Find component by selector

Discussão em 'Angular' iniciado por Francesco Sessa, Setembro 23, 2024.

  1. In Angular, a component is identified by a selector. I am looking for a method to be able to find the component class from its selector.

    I was able to find a method but it does not seem to be very clean; in fact starting from the main module of the application it is necessary to find the injector and loop on the injectorDefTypes. Then, for each imported module, cycle on the declared components and check for matching selectors. I don't like this solution first of all because I had to force some type definitions in order to access some variables of some objects, secondly because I can launch this function only from the main module, and finally because it seems to be quite an onerous operation. Basically I would like to replicate what the angular core does when, parsing the template to be rendered, it identifies the components starting from the selector.

    Here the code of the function i've developed right now:

    private findComponentBySelector(selectorToFind: string) {
    const inj: any = this.moduleRef.injector;
    const types = inj['injectorDefTypes'];
    for (const type of types) {
    if (!type || !type.ɵmod)
    continue;
    for (const comp of type.ɵmod.declarations) {
    if (!comp || !comp.ɵcmp || !comp.ɵcmp.selectors) {
    continue;
    }
    for (const selectors of comp.ɵcmp.selectors) {
    for (const selector of selectors) {
    console.log(selector)
    if (selector === selectorToFind) {
    console.log('found!')
    debugger;
    return comp;
    }
    }

    }
    }
    }
    }


    I've found this question Angular Use Component By Selector Array but it seems to works only for components in the main module.

    On the documentation or at any rate on the net I couldn't find anything about this. Does anyone have any ideas? Thank you very much

    Continue reading...

Compartilhe esta Página