4

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(?);
}
IDK4real
  • 757
  • 6
  • 14
noonecious
  • 63
  • 1
  • 1
  • 6
  • See documentation: https://angular.io/api/core/ViewChild You don't need to instantiate anything. Angular will do that for you and assign the value to that property. You will have to make sure you are trying to access that property only during(or after) one of the proper lifecycle hooks. – peinearydevelopment Jul 28 '21 at 13:59
  • 2
    you need use the `!` in ViewChild to indicate to Angular mode strict that you don't want initialize the variable: @ViewChild('fileInput') fileInput **!** : ElementRef; see e.g. https://indepth.dev/posts/1402/bulletproof-angular for more about the strict mode – Eliseo Jul 28 '21 at 16:10

2 Answers2

1

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
  }
}
IDK4real
  • 757
  • 6
  • 14
0

Instead of:

@ViewChild('fileInput') fileInput: ElementRef;

Use:

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

It should work without any problem.

Jafar Amini
  • 315
  • 2
  • 8