Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elementRef is null after building angular app

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

like image 240
user5329403 Avatar asked Sep 15 '25 09:09

user5329403


1 Answers

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

like image 139
dream88 Avatar answered Sep 17 '25 01:09

dream88