Search code examples
angularangular-router

How to call component from index.html in a hyperlink in Angular 4?


<li><a [router-link]="['/contact']"><strong>Contact</strong></a></li>

I have a navbar present in index.html in which there is a Contact tab. I want to call the Contact component present in my 'app' folder inside the that tab. Below is my syntax that I tried but not working....

My Angular CLI version is 1.4.10


Solution

  • You need to configure your app route, personally I do it in the app.module.ts but you can do it in another file and then import it in your app.module.ts

    import ...
    import { RouterModule, Routes } from '@angular/router';
    
    import { ContactComponent } from 'path of component';
    
    const appRoutes: Routes = [
       {path: 'contact', component: contactComponent}
    ] 
    
    @NgModule({
       declarations: [
          ...,
          ContactComponent
       ],
       imports: [
          BrowserModule,
          RouterModule.forRoot(appRoutes)
       ],
       providers: [],
       bootstrap: [AppComponent]
    })
    
    export class AppModule { }
    

    Then in your navbar, <li><a routerLink="contact"><strong>Contact</strong></a></li>

    Be careful to use <router-outlet></router-outlet> instead of <app-yourAppName></app-yourAppName> to call your principal component in app.component.html, with router-outlet Angular will call the component that you want by clicking on router-link.