Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 12 ViewChild ElementRef

In previous versions of Angular we could just define a ViewChild with an ElementRef like so

@ViewChild('fileInput') fileInput: ElementRef;

Now we have to initialize it in the constructor. ElementRef takes in one argument named nativeElement (here ?):

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

How do we do this for elementRef if there is no default nativeElement?

like image 411
noonecious Avatar asked Nov 02 '25 21:11

noonecious


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
  }
}
like image 195
IDK4real Avatar answered Nov 05 '25 16:11

IDK4real


Instead of:

@ViewChild('fileInput') fileInput: ElementRef;

Use:

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

It should work without any problem.

like image 31
Jafar Amini Avatar answered Nov 05 '25 14:11

Jafar Amini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!