elementRef is null after building angular app












3















In a component template, i'm selecting an svg element with ElementRef. It works fine but when i build the app and open it elementRef is null.



    @Component({
selector: 'app-svg',
template: `<div id="root">
<object [data]='trustedUrl' type="image/svg+xml" height="450" width="650" #dataSvg></object>
</div>`,
styleUrls: ['./svg.component.css']

})
constructor(private sanitizer: DomSanitizer, private elRef: ElementRef) {
}


elementRef targeted



@ViewChild('dataSvg') dataSvg: ElementRef;


pass it to elementRef variable



ngOnInit() {
this.elementRef = this.elRef.nativeElement.querySelector('#dataSvg');
}


after content is loaded, i'm selecting the svg :



ngAfterContentInit() {
const elementRef = this.elementRef;

// when content is loaded...
elementRef.addEventListener('load', function (event) {
// ...retrieve svg element



elementRef.querySelector('svg') is null




when i run 'npm run build' and go to dist/index.html, the contentDocument > is null :



enter image description here










share|improve this question





























    3















    In a component template, i'm selecting an svg element with ElementRef. It works fine but when i build the app and open it elementRef is null.



        @Component({
    selector: 'app-svg',
    template: `<div id="root">
    <object [data]='trustedUrl' type="image/svg+xml" height="450" width="650" #dataSvg></object>
    </div>`,
    styleUrls: ['./svg.component.css']

    })
    constructor(private sanitizer: DomSanitizer, private elRef: ElementRef) {
    }


    elementRef targeted



    @ViewChild('dataSvg') dataSvg: ElementRef;


    pass it to elementRef variable



    ngOnInit() {
    this.elementRef = this.elRef.nativeElement.querySelector('#dataSvg');
    }


    after content is loaded, i'm selecting the svg :



    ngAfterContentInit() {
    const elementRef = this.elementRef;

    // when content is loaded...
    elementRef.addEventListener('load', function (event) {
    // ...retrieve svg element



    elementRef.querySelector('svg') is null




    when i run 'npm run build' and go to dist/index.html, the contentDocument > is null :



    enter image description here










    share|improve this question



























      3












      3








      3








      In a component template, i'm selecting an svg element with ElementRef. It works fine but when i build the app and open it elementRef is null.



          @Component({
      selector: 'app-svg',
      template: `<div id="root">
      <object [data]='trustedUrl' type="image/svg+xml" height="450" width="650" #dataSvg></object>
      </div>`,
      styleUrls: ['./svg.component.css']

      })
      constructor(private sanitizer: DomSanitizer, private elRef: ElementRef) {
      }


      elementRef targeted



      @ViewChild('dataSvg') dataSvg: ElementRef;


      pass it to elementRef variable



      ngOnInit() {
      this.elementRef = this.elRef.nativeElement.querySelector('#dataSvg');
      }


      after content is loaded, i'm selecting the svg :



      ngAfterContentInit() {
      const elementRef = this.elementRef;

      // when content is loaded...
      elementRef.addEventListener('load', function (event) {
      // ...retrieve svg element



      elementRef.querySelector('svg') is null




      when i run 'npm run build' and go to dist/index.html, the contentDocument > is null :



      enter image description here










      share|improve this question
















      In a component template, i'm selecting an svg element with ElementRef. It works fine but when i build the app and open it elementRef is null.



          @Component({
      selector: 'app-svg',
      template: `<div id="root">
      <object [data]='trustedUrl' type="image/svg+xml" height="450" width="650" #dataSvg></object>
      </div>`,
      styleUrls: ['./svg.component.css']

      })
      constructor(private sanitizer: DomSanitizer, private elRef: ElementRef) {
      }


      elementRef targeted



      @ViewChild('dataSvg') dataSvg: ElementRef;


      pass it to elementRef variable



      ngOnInit() {
      this.elementRef = this.elRef.nativeElement.querySelector('#dataSvg');
      }


      after content is loaded, i'm selecting the svg :



      ngAfterContentInit() {
      const elementRef = this.elementRef;

      // when content is loaded...
      elementRef.addEventListener('load', function (event) {
      // ...retrieve svg element



      elementRef.querySelector('svg') is null




      when i run 'npm run build' and go to dist/index.html, the contentDocument > is null :



      enter image description here







      angular dom elementref






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 20 '18 at 16:02







      user5329403

















      asked Nov 20 '18 at 15:20









      user5329403user5329403

      143




      143
























          4 Answers
          4






          active

          oldest

          votes


















          2














          You use @ViewChild('dataSvg') dataSvg: ElementRef; but in your template you haven't provided any anchor for dataSvg.



          There are 2 ways to do this:
          1) using @Directive as explained on Angular Docs
          2) Using a template reference # :in your case:
          <object ... #dataSvg></object>



          Not mentioned if you already use Directive, but in your template code, you only have an id=dataSvg






          share|improve this answer
























          • i did the correct

            – user5329403
            Nov 20 '18 at 16:03











          • uh, but now you have removed the ID part, hence: this.elementRef = this.elRef.nativeElement.querySelector('#dataSvg'); won't work anymore. I'm not really sure, why you do this considering you already have the @viewchild reference

            – dream88
            Nov 20 '18 at 16:40













          • No, it' s fixed i use the elementRef this.dataSvg. the problem is in foreground.. i lose the dynamic comportment when it's not running in node. Svg is not loaded with a dynamic component factory

            – user5329403
            Nov 20 '18 at 17:23



















          2














          According to the official Doc, you cannot access to the @ViewChild element unless you do it in the AfterView hook (AfterViewInit or AfterViewChecked ) instead of the OnInit one.







          • You can find here a good article about differences between @ViewChild, @ViewChildren, @ContentChild and @ContentChildren.






          share|improve this answer

































            1














            DOM is not completely built yet in ngOnInit. You need to wait for children (template here) to be created.



            Instead of ngOnInit, put your code into ngAfterViewInit.



            More info on hooks in component lifecycle can be found in the Angular documentation.






            share|improve this answer
























            • thanks, i did the change on AfterViewInit, but when i'm compiling the app (npm run build) and open index.html into /dist elementRef is null. I want to select the svg child of object element (elementRef.nativeElement.contentDocument)

              – user5329403
              Nov 20 '18 at 15:48



















            0














            I found my solution of compatibility for append SVG element :



            in my svg component i set the source of svg with binding innerHTML, when my input changes i'm loading the svg with a service which returns the svg data in a safe way:



            binding the data source of SVG in the component :



             @Component({
            selector: 'app-svg',
            template: `<div id="root">
            <div [innerHTML]="svgSafe" type="image/svg+xml" height="450" width="650" #dataSvg></div>
            </div>`,
            styleUrls: ['./svg.component.css'] ,
            animations: [

            ]
            })


            load the source of svg with input :



             ngOninit() {

            var url = this.data.url;


            var id = 1;

            if(url === 'assets/object_move.svg') {
            id = 1;
            }

            if(url === 'assets/object_wait.svg') {
            id = 2;
            }


            ..
            var dataSVG;
            this
            .loaderService
            .getSVGData(id)
            .subscribe((dataSvg) => {

            this.svgSafe = this.sanitizer.bypassSecurityTrustHtml(dataSvg.data);

            });
            }





            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%2f53396176%2felementref-is-null-after-building-angular-app%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              2














              You use @ViewChild('dataSvg') dataSvg: ElementRef; but in your template you haven't provided any anchor for dataSvg.



              There are 2 ways to do this:
              1) using @Directive as explained on Angular Docs
              2) Using a template reference # :in your case:
              <object ... #dataSvg></object>



              Not mentioned if you already use Directive, but in your template code, you only have an id=dataSvg






              share|improve this answer
























              • i did the correct

                – user5329403
                Nov 20 '18 at 16:03











              • uh, but now you have removed the ID part, hence: this.elementRef = this.elRef.nativeElement.querySelector('#dataSvg'); won't work anymore. I'm not really sure, why you do this considering you already have the @viewchild reference

                – dream88
                Nov 20 '18 at 16:40













              • No, it' s fixed i use the elementRef this.dataSvg. the problem is in foreground.. i lose the dynamic comportment when it's not running in node. Svg is not loaded with a dynamic component factory

                – user5329403
                Nov 20 '18 at 17:23
















              2














              You use @ViewChild('dataSvg') dataSvg: ElementRef; but in your template you haven't provided any anchor for dataSvg.



              There are 2 ways to do this:
              1) using @Directive as explained on Angular Docs
              2) Using a template reference # :in your case:
              <object ... #dataSvg></object>



              Not mentioned if you already use Directive, but in your template code, you only have an id=dataSvg






              share|improve this answer
























              • i did the correct

                – user5329403
                Nov 20 '18 at 16:03











              • uh, but now you have removed the ID part, hence: this.elementRef = this.elRef.nativeElement.querySelector('#dataSvg'); won't work anymore. I'm not really sure, why you do this considering you already have the @viewchild reference

                – dream88
                Nov 20 '18 at 16:40













              • No, it' s fixed i use the elementRef this.dataSvg. the problem is in foreground.. i lose the dynamic comportment when it's not running in node. Svg is not loaded with a dynamic component factory

                – user5329403
                Nov 20 '18 at 17:23














              2












              2








              2







              You use @ViewChild('dataSvg') dataSvg: ElementRef; but in your template you haven't provided any anchor for dataSvg.



              There are 2 ways to do this:
              1) using @Directive as explained on Angular Docs
              2) Using a template reference # :in your case:
              <object ... #dataSvg></object>



              Not mentioned if you already use Directive, but in your template code, you only have an id=dataSvg






              share|improve this answer













              You use @ViewChild('dataSvg') dataSvg: ElementRef; but in your template you haven't provided any anchor for dataSvg.



              There are 2 ways to do this:
              1) using @Directive as explained on Angular Docs
              2) Using a template reference # :in your case:
              <object ... #dataSvg></object>



              Not mentioned if you already use Directive, but in your template code, you only have an id=dataSvg







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 20 '18 at 15:48









              dream88dream88

              1558




              1558













              • i did the correct

                – user5329403
                Nov 20 '18 at 16:03











              • uh, but now you have removed the ID part, hence: this.elementRef = this.elRef.nativeElement.querySelector('#dataSvg'); won't work anymore. I'm not really sure, why you do this considering you already have the @viewchild reference

                – dream88
                Nov 20 '18 at 16:40













              • No, it' s fixed i use the elementRef this.dataSvg. the problem is in foreground.. i lose the dynamic comportment when it's not running in node. Svg is not loaded with a dynamic component factory

                – user5329403
                Nov 20 '18 at 17:23



















              • i did the correct

                – user5329403
                Nov 20 '18 at 16:03











              • uh, but now you have removed the ID part, hence: this.elementRef = this.elRef.nativeElement.querySelector('#dataSvg'); won't work anymore. I'm not really sure, why you do this considering you already have the @viewchild reference

                – dream88
                Nov 20 '18 at 16:40













              • No, it' s fixed i use the elementRef this.dataSvg. the problem is in foreground.. i lose the dynamic comportment when it's not running in node. Svg is not loaded with a dynamic component factory

                – user5329403
                Nov 20 '18 at 17:23

















              i did the correct

              – user5329403
              Nov 20 '18 at 16:03





              i did the correct

              – user5329403
              Nov 20 '18 at 16:03













              uh, but now you have removed the ID part, hence: this.elementRef = this.elRef.nativeElement.querySelector('#dataSvg'); won't work anymore. I'm not really sure, why you do this considering you already have the @viewchild reference

              – dream88
              Nov 20 '18 at 16:40







              uh, but now you have removed the ID part, hence: this.elementRef = this.elRef.nativeElement.querySelector('#dataSvg'); won't work anymore. I'm not really sure, why you do this considering you already have the @viewchild reference

              – dream88
              Nov 20 '18 at 16:40















              No, it' s fixed i use the elementRef this.dataSvg. the problem is in foreground.. i lose the dynamic comportment when it's not running in node. Svg is not loaded with a dynamic component factory

              – user5329403
              Nov 20 '18 at 17:23





              No, it' s fixed i use the elementRef this.dataSvg. the problem is in foreground.. i lose the dynamic comportment when it's not running in node. Svg is not loaded with a dynamic component factory

              – user5329403
              Nov 20 '18 at 17:23













              2














              According to the official Doc, you cannot access to the @ViewChild element unless you do it in the AfterView hook (AfterViewInit or AfterViewChecked ) instead of the OnInit one.







              • You can find here a good article about differences between @ViewChild, @ViewChildren, @ContentChild and @ContentChildren.






              share|improve this answer






























                2














                According to the official Doc, you cannot access to the @ViewChild element unless you do it in the AfterView hook (AfterViewInit or AfterViewChecked ) instead of the OnInit one.







                • You can find here a good article about differences between @ViewChild, @ViewChildren, @ContentChild and @ContentChildren.






                share|improve this answer




























                  2












                  2








                  2







                  According to the official Doc, you cannot access to the @ViewChild element unless you do it in the AfterView hook (AfterViewInit or AfterViewChecked ) instead of the OnInit one.







                  • You can find here a good article about differences between @ViewChild, @ViewChildren, @ContentChild and @ContentChildren.






                  share|improve this answer















                  According to the official Doc, you cannot access to the @ViewChild element unless you do it in the AfterView hook (AfterViewInit or AfterViewChecked ) instead of the OnInit one.







                  • You can find here a good article about differences between @ViewChild, @ViewChildren, @ContentChild and @ContentChildren.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 20 '18 at 15:49

























                  answered Nov 20 '18 at 15:26









                  selem mnselem mn

                  4,99541939




                  4,99541939























                      1














                      DOM is not completely built yet in ngOnInit. You need to wait for children (template here) to be created.



                      Instead of ngOnInit, put your code into ngAfterViewInit.



                      More info on hooks in component lifecycle can be found in the Angular documentation.






                      share|improve this answer
























                      • thanks, i did the change on AfterViewInit, but when i'm compiling the app (npm run build) and open index.html into /dist elementRef is null. I want to select the svg child of object element (elementRef.nativeElement.contentDocument)

                        – user5329403
                        Nov 20 '18 at 15:48
















                      1














                      DOM is not completely built yet in ngOnInit. You need to wait for children (template here) to be created.



                      Instead of ngOnInit, put your code into ngAfterViewInit.



                      More info on hooks in component lifecycle can be found in the Angular documentation.






                      share|improve this answer
























                      • thanks, i did the change on AfterViewInit, but when i'm compiling the app (npm run build) and open index.html into /dist elementRef is null. I want to select the svg child of object element (elementRef.nativeElement.contentDocument)

                        – user5329403
                        Nov 20 '18 at 15:48














                      1












                      1








                      1







                      DOM is not completely built yet in ngOnInit. You need to wait for children (template here) to be created.



                      Instead of ngOnInit, put your code into ngAfterViewInit.



                      More info on hooks in component lifecycle can be found in the Angular documentation.






                      share|improve this answer













                      DOM is not completely built yet in ngOnInit. You need to wait for children (template here) to be created.



                      Instead of ngOnInit, put your code into ngAfterViewInit.



                      More info on hooks in component lifecycle can be found in the Angular documentation.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Nov 20 '18 at 15:22









                      MicMic

                      2,22211634




                      2,22211634













                      • thanks, i did the change on AfterViewInit, but when i'm compiling the app (npm run build) and open index.html into /dist elementRef is null. I want to select the svg child of object element (elementRef.nativeElement.contentDocument)

                        – user5329403
                        Nov 20 '18 at 15:48



















                      • thanks, i did the change on AfterViewInit, but when i'm compiling the app (npm run build) and open index.html into /dist elementRef is null. I want to select the svg child of object element (elementRef.nativeElement.contentDocument)

                        – user5329403
                        Nov 20 '18 at 15:48

















                      thanks, i did the change on AfterViewInit, but when i'm compiling the app (npm run build) and open index.html into /dist elementRef is null. I want to select the svg child of object element (elementRef.nativeElement.contentDocument)

                      – user5329403
                      Nov 20 '18 at 15:48





                      thanks, i did the change on AfterViewInit, but when i'm compiling the app (npm run build) and open index.html into /dist elementRef is null. I want to select the svg child of object element (elementRef.nativeElement.contentDocument)

                      – user5329403
                      Nov 20 '18 at 15:48











                      0














                      I found my solution of compatibility for append SVG element :



                      in my svg component i set the source of svg with binding innerHTML, when my input changes i'm loading the svg with a service which returns the svg data in a safe way:



                      binding the data source of SVG in the component :



                       @Component({
                      selector: 'app-svg',
                      template: `<div id="root">
                      <div [innerHTML]="svgSafe" type="image/svg+xml" height="450" width="650" #dataSvg></div>
                      </div>`,
                      styleUrls: ['./svg.component.css'] ,
                      animations: [

                      ]
                      })


                      load the source of svg with input :



                       ngOninit() {

                      var url = this.data.url;


                      var id = 1;

                      if(url === 'assets/object_move.svg') {
                      id = 1;
                      }

                      if(url === 'assets/object_wait.svg') {
                      id = 2;
                      }


                      ..
                      var dataSVG;
                      this
                      .loaderService
                      .getSVGData(id)
                      .subscribe((dataSvg) => {

                      this.svgSafe = this.sanitizer.bypassSecurityTrustHtml(dataSvg.data);

                      });
                      }





                      share|improve this answer




























                        0














                        I found my solution of compatibility for append SVG element :



                        in my svg component i set the source of svg with binding innerHTML, when my input changes i'm loading the svg with a service which returns the svg data in a safe way:



                        binding the data source of SVG in the component :



                         @Component({
                        selector: 'app-svg',
                        template: `<div id="root">
                        <div [innerHTML]="svgSafe" type="image/svg+xml" height="450" width="650" #dataSvg></div>
                        </div>`,
                        styleUrls: ['./svg.component.css'] ,
                        animations: [

                        ]
                        })


                        load the source of svg with input :



                         ngOninit() {

                        var url = this.data.url;


                        var id = 1;

                        if(url === 'assets/object_move.svg') {
                        id = 1;
                        }

                        if(url === 'assets/object_wait.svg') {
                        id = 2;
                        }


                        ..
                        var dataSVG;
                        this
                        .loaderService
                        .getSVGData(id)
                        .subscribe((dataSvg) => {

                        this.svgSafe = this.sanitizer.bypassSecurityTrustHtml(dataSvg.data);

                        });
                        }





                        share|improve this answer


























                          0












                          0








                          0







                          I found my solution of compatibility for append SVG element :



                          in my svg component i set the source of svg with binding innerHTML, when my input changes i'm loading the svg with a service which returns the svg data in a safe way:



                          binding the data source of SVG in the component :



                           @Component({
                          selector: 'app-svg',
                          template: `<div id="root">
                          <div [innerHTML]="svgSafe" type="image/svg+xml" height="450" width="650" #dataSvg></div>
                          </div>`,
                          styleUrls: ['./svg.component.css'] ,
                          animations: [

                          ]
                          })


                          load the source of svg with input :



                           ngOninit() {

                          var url = this.data.url;


                          var id = 1;

                          if(url === 'assets/object_move.svg') {
                          id = 1;
                          }

                          if(url === 'assets/object_wait.svg') {
                          id = 2;
                          }


                          ..
                          var dataSVG;
                          this
                          .loaderService
                          .getSVGData(id)
                          .subscribe((dataSvg) => {

                          this.svgSafe = this.sanitizer.bypassSecurityTrustHtml(dataSvg.data);

                          });
                          }





                          share|improve this answer













                          I found my solution of compatibility for append SVG element :



                          in my svg component i set the source of svg with binding innerHTML, when my input changes i'm loading the svg with a service which returns the svg data in a safe way:



                          binding the data source of SVG in the component :



                           @Component({
                          selector: 'app-svg',
                          template: `<div id="root">
                          <div [innerHTML]="svgSafe" type="image/svg+xml" height="450" width="650" #dataSvg></div>
                          </div>`,
                          styleUrls: ['./svg.component.css'] ,
                          animations: [

                          ]
                          })


                          load the source of svg with input :



                           ngOninit() {

                          var url = this.data.url;


                          var id = 1;

                          if(url === 'assets/object_move.svg') {
                          id = 1;
                          }

                          if(url === 'assets/object_wait.svg') {
                          id = 2;
                          }


                          ..
                          var dataSVG;
                          this
                          .loaderService
                          .getSVGData(id)
                          .subscribe((dataSvg) => {

                          this.svgSafe = this.sanitizer.bypassSecurityTrustHtml(dataSvg.data);

                          });
                          }






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 28 '18 at 9:42









                          user5329403user5329403

                          143




                          143






























                              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%2f53396176%2felementref-is-null-after-building-angular-app%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

                              'app-layout' is not a known element: how to share Component with different Modules

                              android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                              WPF add header to Image with URL pettitions [duplicate]