Home > Back-end >  Angular 13 inherited class cannot access ViewChild
Angular 13 inherited class cannot access ViewChild

Time:11-20

I am unable to use ViewChild with a string reference due to Angular sanitizing the #id tag from my HTML template.

template.html

        
    <div [ngClass]="htmlClass">
        <a #inset name="inset"  [ngClass]="htmlClass"></a>
    </div>

my-component.ts

    export class MyComponent extends BaseComponent {       

        public htmlClass = "dashboard-widget DASHBOARD";
        constructor() {
          super();
        }

base-component.ts

    @Injectable()
    export abstract class BaseComponent implements AfterViewInit {       
        @ViewChild('inset') contentInsetView: any;
    }

This results in the following rendered HTML:

        
    <div _ngcontent-dkm-c114=""  ng-reflect-ng->
        <a _ngcontent-dkm-c114="" name="inset"  ng-reflect-ng-></a>
    </div>

This results in the view child never being set:

      ngAfterViewInit() {
        console.warn("AfterInit: ", this.contentInsetView);
      }

    AfterInit:  undefined

This code was working in prior Angular versions (version 9), any ideas?

UPDATED: Added inherited class which seems to be causing the problem.

CodePudding user response:

You need to tell angular what it should read from inset.

The correct way to use @ViewChild is:

@ViewChild('selector', { read: ElementRef }) element?: ElementRef<HTMLElement>

If I know, that the selector will never disappear (is not inside a *ngIf), I give ViewChild decorator static: true and element!: ElementRef<...>.

@ViewChild('selector', { read: ElementRef, static: true }) element!: ElementRef<HTMLElement>

I do this because the static means, that when ngOnInit hook is fired, the element will be defined, and it is mostly safe to use it everywhere.

CodePudding user response:

Found the issue.

In order to inherit a Component in angular you must create another component complete with @Component decorator.

  • Related