Search code examples
angulardocument-ready

Angular 9 - Equivalent of $(document).ready()


What is the Angular equivalent of $(document).ready() ?

I want to execute a method once when the document is fully loaded (the method creates a component inside my component).

None of the angular lifecyle hook is working (the console output that this is undefined in the early stages of the lifecycle, meaning that the component/class is not instanciated. On the late stages, the component is created a large number of times, ultimately freezing the navigator.)


Solution

  • I solved it, so to answer the question : the angular hook ngAfterViewInit is an equivalent of $(document).ready().

    I do not say it is the only way, as it may depend of what you are trying to do (I am new to Angular, so I can not be sure).

    Here is the code. It is more about a way to create a child component after the document is ready than it is about calling a method once the document is ready, so most of it is beyond the scope of the question.


    HTML

    <div>
        <!-- Template that can contain multiple components of any kind. 
             I want it to contain a 'ComponentA' before the page is rendered. -->
        <template #containerForChildrenComponents></template>
    </div>
    

    TypeSript

    export class MainComponent implements AfterViewInit {
    
        @ViewChild('containerForChildrenComponents', {read: ViewContainerRef}) entry: ViewContainerRef;
    
        constructor(private readonly resolver: ComponentFactoryResolver,
                    private readonly changeDetectorRef: ChangeDetectorRef) {
        }
    
        ngAfterViewInit(): void {
            // Call the method creating a child component of class 'ComponentA' inside the template
            this.createChildComponentA();
            this.changeDetectorRef.detectChanges();
        }
    
        createChildComponentA() {
            const factory = this.resolver.resolveComponentFactory(ComponentA);
            const componentRef = this.entry.createComponent(factory);
            // ...
        }
    }