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.?
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.
ElementReflinkA wrapper around a native element inside of a View.
You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor: constructor(private myElement: ElementRef) { ... }
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With