Angular 12 ViewChild ElementRef

Viewed 8074

In previous versions of angular we could just define a viewchild with an element ref like so

@ViewChild('fileInput') fileInput: ElementRef;

Now we have to initialize it in the constructor? how do we do this for elementRef if there is no default nativeelement? Element Ref takes in one argument https://angular.io/api/core/ElementRef

constructor() {
    this.fileInput = new ElementRef(?);
}
2 Answers

If you want to gain access to the ViewChild element, you can only do it after the AfterViewInit/AfterViewChecked lifecycle has been taken its course. You don't need to manually create it, Angular will do that for you. You can do see this occur in Angular Example 2.

However, keep in mind, it is not possible to have access to it in the constructor, ngOnInit.

If you want access to your own element component ElementRef you can do it has follows:

@Component(...)
export class CustomComponent {
  constructor(elementRef: ElementRef) {
    // Code here or store it via an attribute accessor
  }
}

Instead of:

@ViewChild('fileInput') fileInput: ElementRef;

Use:

@ViewChild('fileInput') fileInput!: ElementRef;

It should work without any problem.

Related