Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the state of ElementRef when it's available in components constructor

I can get access to ElementRef in components constructor:

export class MyComponent {
    constructor(element: ElementRef) {
       element.nativeElement

What is the state of this DOM element:

1) in terms of DOM - is it put in the DOM already? Is it rendered? Are it's child components DOM elements created and appended?

2) in terms of child components lifecycle - what stages have child components gone through - onInit, afterContentInit etc.?

like image 639
Max Koretskyi Avatar asked Nov 17 '16 16:11

Max Koretskyi


People also ask

How do I get ElementRef from components?

Getting ElementRef in Component ClassCreate a template reference variable for the element in the component/directive. Use the template variable to inject the element into component class using the ViewChild or ViewChildren.

What is ElementRef in angular?

ElementReflinkA wrapper around a native element inside of a View.

Can we access DOM element inside angular component constructor method?

You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor: constructor(private myElement: ElementRef) { ... }

How do you use ElementRef in angular 10?

We first import ElementRef from the @angular/core package, next we inject it via the directive's constructor. Next, in the ngOnInit method of the directive we use the nativeElement interface of ElementRef to access the native style property of the DOM element to which the directive is applied.


1 Answers

Internally each Angular component is represented as an element and a directive. You can read more about it in the Here is why you will not find components inside Angular.

The elementRef that you can inject into the constructor is actually the element used to host a component. Now to your questions.

1) in terms of DOM - is it put in the DOM already? Is it rendered? Are it's child components DOM elements created and appended?

Yes, it's created and appended to the parent DOM element. It's not yet rendered as the process of bootstrapping components synchronous so a browser doesn't have a chance for repaint. No, its child components are not created yet.

2) in terms of child components lifecycle - what stages have child components gone through - onInit, afterContentInit etc.?

All lifecycle hooks are part of change detection. Read more in Everything you need to know about change detection in Angular. And the components tree is created before change detection. So no lifecycle hooks has been triggered for this component and as I said above no children have been created yet.

like image 81
Max Koretskyi Avatar answered Sep 18 '22 18:09

Max Koretskyi