Angularv4.初体验


1825 浏览 5 years, 2 months

13 轮播图 ngx bootstrap carousel

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

创建一个主页模块

ng g component home 报错 > Could not find an NgModule. Use the skip-import option to skip importing in NgModule

https://github.com/angular/angular-cli/wiki/generate-component

应该是升级没弄好,修改angular.json

    "srvup-e2e": {
      "root": "e2e/",

再次运行就好了

除了生成home目录,它同时也会更新app.modules.ts,将HomeComponent添加到NgModule里

import { HomeComponent } from './home/home.component';

接下来将主页路由指向这个模块。

import { HomeComponent } from './home/home.component';

const appRoutes: Routes = [
  {
    path:"",
    component:HomeComponent,
  },

访问http://127.0.0.1:4200/, home works!

下面我们将在主页添加carousel模块

访问https://valor-software.com/ngx-bootstrap/#/carousel,按照上面的步骤一步一步来操作。

在app.modules.ts添加carousel模块

import { CarouselModule } from 'ngx-bootstrap/carousel';
@NgModule({
  imports: [
    CarouselModule.forRoot(),

拷贝https://valor-software.com/ngx-bootstrap/#/carousel#captions例子代码到home.component.html

<carousel>
  <slide>
    <img src="assets/images/nature/4.jpg" alt="first slide" style="display: block; width: 100%;">
    <div class="carousel-caption d-none d-md-block">
      <h3>First slide label</h3>
      <p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p>
    </div>
  </slide>
  <slide>
    <img src="assets/images/nature/5.jpg" alt="second slide" style="display: block; width: 100%;">
    <div class="carousel-caption d-none d-md-block">
      <h3>Second slide label</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
  </slide>
  <slide>
    <img src="assets/images/nature/6.jpg" alt="third slide" style="display: block; width: 100%;">
    <div class="carousel-caption d-none d-md-block">
      <h3>Third slide label</h3>
      <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur.</p>
    </div>
  </slide>
</carousel>

根据代码例子中的静态文件路径assets/images/nature/4.jpg,在项目工程中添加对应的图片文件,改完之后效果就出来了。

如果图片大小不一样的话,图片显示效果会受影响。

稍微做一些调整

  • 给image添加class img-main-carousel,并在style.css定义这个class,设置max-height=500px;,这样所有图片高度会一致
  • 给image添加class img-responsive,让图片比例缩放。注意要删除默认stylestyle="display: block; width: 100%;",否则宽度不能自动缩放。

下面添加jumbotron,参考https://getbootstrap.com/docs/3.3/components/#jumbotron,将前面的carousel添加到下面的框架里

<div class="jumbotron">
  <div class="container">
    ...
  </div>
</div>

carousel左右两边有两个箭头控制图片切换,怎么确认鼠标已经在切换区域了呢?添加cursor:pointer;样式。

.carousel-control.right, .carousel-control.left{
    cursor: pointer;
}

最后,我们给页面添加一些链接,给图片及按钮添加下面链接

<a class="btn btn-default" href="/videos/video-1"> Video 1</a>

<a class="" href="/videos/video-1"><img class="img-main-carousel img-responsive" src="assets/images/nature/4.jpg" alt="first slide" ></a>

最终效果