javascripthtmlangularangular2-routing

body content has to be update without header and footer change and no page refresh


I have a header menu with buttons "home" and "about us". By default home page loads. In the home page, i have a link in the home page. when i click on the link on the home page or "about us" button, the body content has to be changed in the home page but page should not be refresh. "About us" related data has to be display. Header and footer page is common for all pages and only body content has to be updated without page refresh. I don't want to use any jquery or no server call here.


Solution

  • What you are looking for is Router. See the official Angular 2 docs on routing and navigation to get a more detailed view on this subject.

    I've set up a Plunker to give you a basic example of routing in Angular 2.

    The routing happens in a new file, called app.routing.ts, see below for the important parts:

    import { HomeComponent }  from './home.component';
    import { AboutUsComponent }    from './aboutus.component';
    
    const appRoutes: Routes = [
      { path: '', component: HomeComponent },
      { path: 'aboutus', component: AboutUsComponent }
    ];
    

    First you import the components (like pages) where you want to navigate to and after that you set the paths for it to navigate to (like the url in the address bar). path: 'aboutus', component: AboutUsComponent will load the AboutUsComponent when navigating to foo.com/aboutus.

    In the HTML, the main changes are that you don't use <a href="/aboutus">, but <a routerLink="/aboutus"</a>, so Angular knows where to navigate to (see code below).

    <nav>
      <a routerLink="">Home</a>
      <a routerLink="/aboutus">About us</a>
    </nav>
    

    Play around with the code and see the documentation in order to get the hang out of it.