Angularv4.初体验


1569 浏览 5 years, 10 months

24 路由和导航 Router Link & Improved Navigation

版权声明: 转载请注明出处 http://www.codingsoho.com/

我们很多地方依然用的是href,这个没问题,但是有更好的方法,可以用routerLink

修改导航条内容,将href都替换为angular的routerLink

src/app/app.component.html

      <!-- <a class="navbar-brand" href="#">Srvup</a>  -->
      <a class="navbar-brand" routerLink='' routerLinkActive="active">Srvup</a>   
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
    <!--
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
        <li><a href="#">Link</a></li>
        <li class="dropdown" dropdown>
          <a href="#" dropdownToggle class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
          <ul *dropdownMenu class="dropdown-menu">
            <li><a href="#">Action</a></li>
            <li><a href="#">Another action</a></li>
            <li><a href="#">Something else here</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">Separated link</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">One more separated link</a></li>
          </ul>
        </li>
      </ul>
      -->
      <search [passedQuery]='query'></search>
       <ul class="nav navbar-nav navbar-right">
        <!-- <li><a href="#">Link</a></li> -->
        <li routerLink='/videos/' routerLinkActive="active"><a routerLink='/videos/' routerLinkActive="active">Videos</a></li>    

上面删除了一些不用的内容

将srvup和video添加routerLinkActive属性,在当前页面他们跟正常<a>元素基本一致,点击他们navigate到新的网页时,该<a>会处于激活显示

主页时,videos未处于active状态

导航到video-list页面时,videos处于激活中

同样修改其他的href为routeLink,并添加属性routerLinkActive

src/app/video-list/video-list.component.html

    <!-- <h1><a href='videos/{{ abc.slug }}' >{{ abc.name }}</a></h1> -->
    <h1><a routerLink='/videos/{{ abc.slug }}' routerLinkActive="active">{{ abc.name }}</a></h1>

src/app/search-detail/search-detail.component.html

    <!-- <h1><a href='videos/{{ abc.slug }}' >{{ abc.name }}</a></h1> -->
    <h1><a routerLink='/videos/{{ abc.slug }}' routerLinkActive="active">{{ abc.name }}</a></h1>                  

src/app/home/home.component.html

                <!-- <a class='' href='/videos/video-1' (click)='preventNormal($event, imageObj)'> -->
                <a class='' routerLink='/videos/{{ imageObj.slug }}' routerLinkActive="active">     

                  <!-- <p><a class='btn btn-default' href='/videos/{{ imageObj.slug }}'>View</a></p>  -->
                  <p><a class='btn btn-default' routerLink='/videos/{{ imageObj.slug }}' routerLinkActive="active">View</a></p>