Angular 7 resolve component factory from selectorHow to define an Angular 2 component or directive with multiple selectorsAngular 2 global componentWhen does Angular create component instancesShould I create a module per component in Angular 4+ app?Angular - Using a component across multiple modulesAngular 5.2.4 AOT compile throws “Cannot Determine Module for Class” errorReplace Angular Component with anotherHow do we inject component in ng-template via URL in angular 5?How to avoid exposing internal component in AngularHow to pass content in between Angular child component selectors

Do you know your 'KVZ's?

Why are they 'nude photos'?

How to find the object of reference of a latin relative pronoun?

Single word for "refusing to move to next activity unless present one is completed."

Is a request to book a business flight ticket for a graduate student an unreasonable one?

For a hashing function like MD5, how similar can two plaintext strings be and still generate the same hash?

Graduate student with abysmal English writing skills, how to help

Use of って when quotation doesn't make sense

How to evolve human-like eyes that can stare at the sun without protection?

Why didn't Thanos kill all the Dwarves on Nidavellir?

How to memorize multiple pieces?

Is there any word for "disobedience to God"?

What is a solution?

How can I effectively communicate to recruiters that a phone call is not possible?

Civil War story: man hanged from a bridge

Fivenum and a little bit

During copyediting, journal disagrees about spelling of paper's main topic

Translating the "organ registration" in Spanish?

Where should I connect my modem in this ethernet junction box?

How to tell someone I'd like to become friends without letting them think I'm romantically interested in them?

Referring to different instances of the same character in time travel

RPI3B+: What are the four components below the HDMI connector called?

Would dual wielding daggers be a viable choice for a covert bodyguard?

Received a dinner invitation through my employer's email, is it ok to attend?



Angular 7 resolve component factory from selector


How to define an Angular 2 component or directive with multiple selectorsAngular 2 global componentWhen does Angular create component instancesShould I create a module per component in Angular 4+ app?Angular - Using a component across multiple modulesAngular 5.2.4 AOT compile throws “Cannot Determine Module for Class” errorReplace Angular Component with anotherHow do we inject component in ng-template via URL in angular 5?How to avoid exposing internal component in AngularHow to pass content in between Angular child component selectors






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm developing an Angular 7 lib that has knowledge of a previously declared component (in same or higher module). I have the component selector only at this point, and wish to create that component in container view.



Can that be done? Can I get factory from compiler internals without maintaining a registry of my own?



Thanks










share|improve this question




























    0















    I'm developing an Angular 7 lib that has knowledge of a previously declared component (in same or higher module). I have the component selector only at this point, and wish to create that component in container view.



    Can that be done? Can I get factory from compiler internals without maintaining a registry of my own?



    Thanks










    share|improve this question
























      0












      0








      0








      I'm developing an Angular 7 lib that has knowledge of a previously declared component (in same or higher module). I have the component selector only at this point, and wish to create that component in container view.



      Can that be done? Can I get factory from compiler internals without maintaining a registry of my own?



      Thanks










      share|improve this question














      I'm developing an Angular 7 lib that has knowledge of a previously declared component (in same or higher module). I have the component selector only at this point, and wish to create that component in container view.



      Can that be done? Can I get factory from compiler internals without maintaining a registry of my own?



      Thanks







      angular






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 26 at 2:20









      user2009677user2009677

      3924 silver badges8 bronze badges




      3924 silver badges8 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          0














          The below method will work if you can get the Module that declares the component as well as the component's selector.



          First, create a helper method to get decorator annotations off of types (I do not believe that this will work with IE or aot compilation):



          /**
          * gets a decorator of the requested type off of the given decorated type
          * @param decoratedType to get decorator annotations off of
          * @param decoratorType to search for out of all the decorators on decoratedType
          * @returns decorator from the decoratedType of the decoratorType
          */
          export function decoratorOfType<T>(decoratedType: Type<any>, decoratorType: Type<T>): T
          // get all decorators off of the provided type
          return Reflect.getOwnPropertyDescriptor(decoratedType, '__annotations__').value.find((annotation: any) =>
          // get the decorator that matches the requested type
          annotation instanceof decoratorType
          );



          This function will make it easy to get the @NgModule decorator of the module that the component is declared in (AppModule in my example):



          const ngModuleDecorator = decoratorOfType(AppModule, NgModule);


          Using the module decorator you can go through its declarations and find ones with the @Component decorator and a selector set to what you are looking for (app-counter in my example).



          const componentType = ngModuleDecorator.declarations.find((declaration: Type<any>) => 
          // get the @Component decorator
          const declarationDecorator = decoratorOfType(declaration, Component);

          // find a declaration with the @Component decorator (not a @Directive) with the requested selector
          return declarationDecorator != null && declarationDecorator.selector === 'app-counter';
          );


          After you have the component's type you can create the component using a ViewContainerRef and the ComponentFactoryResolver just like other tutorials show you how to dynamically create components:



          // get the component factory using the component type
          const componentFactory = this._componentFactoryResolver.resolveComponentFactory(componentType as Type<any>);

          // fill the content using the component factory
          this.dynamicContentDiv.clear();
          this.dynamicContentDiv.createComponent(componentFactory);


          I have created a working example on StackBlitz that switches between two components depending on what the selected selector is:






          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55348949%2fangular-7-resolve-component-factory-from-selector%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            The below method will work if you can get the Module that declares the component as well as the component's selector.



            First, create a helper method to get decorator annotations off of types (I do not believe that this will work with IE or aot compilation):



            /**
            * gets a decorator of the requested type off of the given decorated type
            * @param decoratedType to get decorator annotations off of
            * @param decoratorType to search for out of all the decorators on decoratedType
            * @returns decorator from the decoratedType of the decoratorType
            */
            export function decoratorOfType<T>(decoratedType: Type<any>, decoratorType: Type<T>): T
            // get all decorators off of the provided type
            return Reflect.getOwnPropertyDescriptor(decoratedType, '__annotations__').value.find((annotation: any) =>
            // get the decorator that matches the requested type
            annotation instanceof decoratorType
            );



            This function will make it easy to get the @NgModule decorator of the module that the component is declared in (AppModule in my example):



            const ngModuleDecorator = decoratorOfType(AppModule, NgModule);


            Using the module decorator you can go through its declarations and find ones with the @Component decorator and a selector set to what you are looking for (app-counter in my example).



            const componentType = ngModuleDecorator.declarations.find((declaration: Type<any>) => 
            // get the @Component decorator
            const declarationDecorator = decoratorOfType(declaration, Component);

            // find a declaration with the @Component decorator (not a @Directive) with the requested selector
            return declarationDecorator != null && declarationDecorator.selector === 'app-counter';
            );


            After you have the component's type you can create the component using a ViewContainerRef and the ComponentFactoryResolver just like other tutorials show you how to dynamically create components:



            // get the component factory using the component type
            const componentFactory = this._componentFactoryResolver.resolveComponentFactory(componentType as Type<any>);

            // fill the content using the component factory
            this.dynamicContentDiv.clear();
            this.dynamicContentDiv.createComponent(componentFactory);


            I have created a working example on StackBlitz that switches between two components depending on what the selected selector is:






            share|improve this answer



























              0














              The below method will work if you can get the Module that declares the component as well as the component's selector.



              First, create a helper method to get decorator annotations off of types (I do not believe that this will work with IE or aot compilation):



              /**
              * gets a decorator of the requested type off of the given decorated type
              * @param decoratedType to get decorator annotations off of
              * @param decoratorType to search for out of all the decorators on decoratedType
              * @returns decorator from the decoratedType of the decoratorType
              */
              export function decoratorOfType<T>(decoratedType: Type<any>, decoratorType: Type<T>): T
              // get all decorators off of the provided type
              return Reflect.getOwnPropertyDescriptor(decoratedType, '__annotations__').value.find((annotation: any) =>
              // get the decorator that matches the requested type
              annotation instanceof decoratorType
              );



              This function will make it easy to get the @NgModule decorator of the module that the component is declared in (AppModule in my example):



              const ngModuleDecorator = decoratorOfType(AppModule, NgModule);


              Using the module decorator you can go through its declarations and find ones with the @Component decorator and a selector set to what you are looking for (app-counter in my example).



              const componentType = ngModuleDecorator.declarations.find((declaration: Type<any>) => 
              // get the @Component decorator
              const declarationDecorator = decoratorOfType(declaration, Component);

              // find a declaration with the @Component decorator (not a @Directive) with the requested selector
              return declarationDecorator != null && declarationDecorator.selector === 'app-counter';
              );


              After you have the component's type you can create the component using a ViewContainerRef and the ComponentFactoryResolver just like other tutorials show you how to dynamically create components:



              // get the component factory using the component type
              const componentFactory = this._componentFactoryResolver.resolveComponentFactory(componentType as Type<any>);

              // fill the content using the component factory
              this.dynamicContentDiv.clear();
              this.dynamicContentDiv.createComponent(componentFactory);


              I have created a working example on StackBlitz that switches between two components depending on what the selected selector is:






              share|improve this answer

























                0












                0








                0







                The below method will work if you can get the Module that declares the component as well as the component's selector.



                First, create a helper method to get decorator annotations off of types (I do not believe that this will work with IE or aot compilation):



                /**
                * gets a decorator of the requested type off of the given decorated type
                * @param decoratedType to get decorator annotations off of
                * @param decoratorType to search for out of all the decorators on decoratedType
                * @returns decorator from the decoratedType of the decoratorType
                */
                export function decoratorOfType<T>(decoratedType: Type<any>, decoratorType: Type<T>): T
                // get all decorators off of the provided type
                return Reflect.getOwnPropertyDescriptor(decoratedType, '__annotations__').value.find((annotation: any) =>
                // get the decorator that matches the requested type
                annotation instanceof decoratorType
                );



                This function will make it easy to get the @NgModule decorator of the module that the component is declared in (AppModule in my example):



                const ngModuleDecorator = decoratorOfType(AppModule, NgModule);


                Using the module decorator you can go through its declarations and find ones with the @Component decorator and a selector set to what you are looking for (app-counter in my example).



                const componentType = ngModuleDecorator.declarations.find((declaration: Type<any>) => 
                // get the @Component decorator
                const declarationDecorator = decoratorOfType(declaration, Component);

                // find a declaration with the @Component decorator (not a @Directive) with the requested selector
                return declarationDecorator != null && declarationDecorator.selector === 'app-counter';
                );


                After you have the component's type you can create the component using a ViewContainerRef and the ComponentFactoryResolver just like other tutorials show you how to dynamically create components:



                // get the component factory using the component type
                const componentFactory = this._componentFactoryResolver.resolveComponentFactory(componentType as Type<any>);

                // fill the content using the component factory
                this.dynamicContentDiv.clear();
                this.dynamicContentDiv.createComponent(componentFactory);


                I have created a working example on StackBlitz that switches between two components depending on what the selected selector is:






                share|improve this answer













                The below method will work if you can get the Module that declares the component as well as the component's selector.



                First, create a helper method to get decorator annotations off of types (I do not believe that this will work with IE or aot compilation):



                /**
                * gets a decorator of the requested type off of the given decorated type
                * @param decoratedType to get decorator annotations off of
                * @param decoratorType to search for out of all the decorators on decoratedType
                * @returns decorator from the decoratedType of the decoratorType
                */
                export function decoratorOfType<T>(decoratedType: Type<any>, decoratorType: Type<T>): T
                // get all decorators off of the provided type
                return Reflect.getOwnPropertyDescriptor(decoratedType, '__annotations__').value.find((annotation: any) =>
                // get the decorator that matches the requested type
                annotation instanceof decoratorType
                );



                This function will make it easy to get the @NgModule decorator of the module that the component is declared in (AppModule in my example):



                const ngModuleDecorator = decoratorOfType(AppModule, NgModule);


                Using the module decorator you can go through its declarations and find ones with the @Component decorator and a selector set to what you are looking for (app-counter in my example).



                const componentType = ngModuleDecorator.declarations.find((declaration: Type<any>) => 
                // get the @Component decorator
                const declarationDecorator = decoratorOfType(declaration, Component);

                // find a declaration with the @Component decorator (not a @Directive) with the requested selector
                return declarationDecorator != null && declarationDecorator.selector === 'app-counter';
                );


                After you have the component's type you can create the component using a ViewContainerRef and the ComponentFactoryResolver just like other tutorials show you how to dynamically create components:



                // get the component factory using the component type
                const componentFactory = this._componentFactoryResolver.resolveComponentFactory(componentType as Type<any>);

                // fill the content using the component factory
                this.dynamicContentDiv.clear();
                this.dynamicContentDiv.createComponent(componentFactory);


                I have created a working example on StackBlitz that switches between two components depending on what the selected selector is:







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Apr 8 at 1:19









                Dustin EastwayDustin Eastway

                11 bronze badge




                11 bronze badge


















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55348949%2fangular-7-resolve-component-factory-from-selector%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                    155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해