Wanted to update Dom elements like Image and Text after loading component in Angular. Note: Both of them does not have ID but have Class Name.
I used following code:
@ViewChild('.appnametitle') el: ElementRef;
constructor(
private renderer: Renderer2,
@Inject(DOCUMENT) private document,
@Inject(ONEPLACE_JS_URI) private oneplaceJsUri,
public cookieConfig: CookieConfig
) { }
ngAfterViewInit(): void {
this.renderer.setAttribute(this.el.nativeElement, 'innerHTML', 'Test Title Change');
}
but it shows following error: Cannot read properties of undefined (reading 'nativeElement')
Could you help me where I am doing it wrong?
ViewChild has not a classname as selector (a directive yes). So you can create a directive with the selector of the class and use ViewChild asking about the directive
@Directive({
selector: '.appnametitle'
})
export class SelectDirective {
constructor(public el:ElementRef) { }
}
And in Component:
@ViewChild(SelectDirective) selectDirective:SelectDirective
ngAfterViewInit(): void {
this.renderer.setAttribute(this.selectDirective.el.nativeElement,
'innerHTML', 'Test Title Change');
}
But this is used if you has not access to the component (because was on third persons, e.g.), else you should rethinking the problem in a more angular way