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 :
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 intongAfterViewInit
.More info on hooks in component lifecycle can be found in the Angular documentation.