Issue
I want to create a simple routing for the app. My problem is that when I change the url to .../myComponent. The Component is rendered but together with the context of another Component referenced in app.component.html However I like to navigate "away" from the main Component to the actual component so I only see the context of this component.
It seems very simple however I stuck here for a while and not quite understand the problem. I think the implementation is not correct since with using router-outlet in the app.component.html it will rendered in this place..
{
path: 'myComponent', component: myComponent
},
]
@NgModule({
RouterModule.forRoot(routes, {initialNavigation: 'enabledBlocking'}),
],
....
app.component.html
<other-selector></other-selector>
<router-outlet></router-outlet>
MyComponent
export class MyComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit(): void {
this.router.navigate(['/myComponent']);
}
}
So my goal is simply to render myComponent when changing url to localhost:..../myComponent
Can someone please tell me what I am missing?
Solution
you can use an *ngIf
directive to show and hide your app component when you redirected to myComponent
.You need to check the requested url using angular routerEvent
,and you can set the boolean value based on your condition to the variable.
app.component.ts
constructor(router: Router) {
router.events.forEach((event) => {
if (event instanceof NavigationStart) {
this.showOtherComponent = event.url !== '/myComponent';
}
});
}
app.component.html
<app-main-component *ngIf="showOtherComponent"></app-main-component>
<router-outlet></router-outlet>
reference:
Answered By - hafizi hamid
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.