Angularv4.初体验


1464 浏览 5 years, 10 months

26 类样式 ngClass

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

如果我增加video的数量,

src/assets/json/videos.json

    {
      "name": "4",
      "slug": "item-4",
      "embed": "1hyjLD7pk10",
      "image": "assets/images/nature/4.jpg",
      "featured": true
     },
     {
      "name": "Item 5",
      "slug": "item-5",
      "embed": "1hyjLD7pk10",
      "image": "assets/images/nature/5.jpg",
      "featured": true
     },
     {
      "name": "Item 6",
      "slug": "item-6",
      "embed": null,
      "image": "assets/images/nature/6.jpg"
     },
     {
      "name": "Item 7",
      "slug": "item-7",
      "embed": "1hyjLD7pk10",
      "image": "assets/images/nature/4.jpg",
      "featured": true
     },
     {
      "name": "Item 8",
      "slug": "item-8",
      "embed": "1hyjLD7pk10",
      "image": "assets/images/nature/5.jpg",
      "featured": true
     },
     {
      "name": "Item 9",
      "slug": "item-9",
      "embed": null,
      "image": "assets/images/nature/6.jpg"
     },
     {
      "name": "Item 10",
      "slug": "item-10",
      "embed": "1hyjLD7pk10",
      "image": "assets/images/nature/4.jpg",
      "featured": true
     },
     {
      "name": "Item 11",
      "slug": "item-11",
      "embed": "1hyjLD7pk10",
      "image": "assets/images/nature/5.jpg",
      "featured": true
     },
     {
      "name": "Item 12",
      "slug": "item-12",
      "embed": null,
      "image": "assets/images/nature/6.jpg"
     }

列表显示效果如下,这个是bootstarps的特性,Item3高度偏小,Item4首先填充了。

如果想让item 3 自动换行效果呈现,最好这儿另起一个新行row。
之前我们用cycle来解决了这个问题,这儿打算用angular的特性来处理。

修改代码如下,我们添加了ngClass, (i+1)%3 == 0 表示每隔三个元素。如果改成 (i+1)%4==0,那么会每行4个。

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

<div *ngFor='let abc of videoList; let i = index' [ngClass]="{'row': (i+1)%3 == 0}">
     <div class='col-md-4 col-sm-12' >
        <div class="thumbnail">
           <a routerLink='/videos/{{ abc.slug }}' routerLinkActive="active" *ngIf='abc.image'><img [src]='abc.image' alt="{{ abc.name }} image"></a>
           <div class="caption">

另外col class从”col-sm-4”改成了”col-md-4 col-sm-12”,这样在小屏幕上时,会自适应为每行一个图片

对应的html如下

这儿有个问题是内容不是从row开始的,前面两个column并没有在row里面
如果用[ngClass]="{'row': (i+1)%3 == 0, 'row': i== 0}",第一个vide包含在row里面,但是第二个和第三个又有问题,因为他们在col-sm-4上面还报了一层div,即使这个div没有row class
这个问题留到以后解决吧

额外做了个小修改,将title放到col里面,这样,它会跟列表的排版更协调一点

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

<div class='row'>
     <div class='col-sm-12'>
         <h1>
           {{ title }}
         </h1>
     </div>
 </div>

同样的方法修改搜索结果列表

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

<div class='row'>
     <div class='col-sm-4' *ngFor='let abc of videoList'>
 <div *ngFor='let abc of videoList; let i = index' [ngClass]="{'row': (i+1)%3 == 0}">
     <div class='col-md-4 col-sm-12' >