Reputation: 23
Do you know how to load a page, then one of the components inside?
For example, I have a page with a navigation bar and an API call component (which displays a table).
I'd like the page to load, we see the navigation bar, and only then the API call component is activated.
Thank you!
Upvotes: 2
Views: 2639
Reputation: 23
For those who use the router-outlet, and tags for urls, for example in header, you can use the routerLink to load only the component inside (I discovered this recently).
By having a "home" path, for example you can :
<a routerLink="/home">Home</a>
Some docs: FRENCH: https://guide-angular.wishtack.io/angular/routing/mise-en-place-du-routing
ENGLISH: https://www.pluralsight.com/guides/activating-routes-with-routerllink-in-angular
Upvotes: 0
Reputation: 3975
Here's a quick StackBlitz I threw together for you, just move the request piece accordingly into the needed lifecycle event.
I should mention, it would be best practice to move the actual request into a service and then from the component fire the request.
import {
Component,
OnInit,
AfterViewInit
} from '@angular/core';
import {
HttpClient
} from '@angular/common/http';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterViewInit {
todos: Array < Todo > ;
constructor(private http: HttpClient) {
this.http.get('https://jsonplaceholder.typicode.com/todos').subscribe((data: Todo[]) => {
this.todos = data;
});
}
ngOnInit(): void {
console.log('ngOnInit');
}
ngAfterViewInit(): void {
console.log('ngAfterViewInit');
}
}
export interface Todo {
userId: number;
id: number;
title: string;
completed: boolean;
}
Upvotes: 0
Reputation: 1453
You can use ngAfterViewInit life cycle hook to ensure the statements are executed after view is completely initialized.
You can read more about that here
Essentially, you will need to do ::
export SomeComponent implements AfterViewInit
ngAfterViewInit() {}
If you are placing nav-bar in seperate component and populating the api data in a separate component, please do the following ::
Inside your navigation component,
In HTML : you can place the <router-outlet></router-outlet>
In TS: Inside ngAfterViewInit()
, do router.navigate()
Please add a comment if you feel you need more help on this :)
Upvotes: 0