首页 > 解决方案 > Angular:如何从 ng-bootstrap 导入和使用 Carousel?

问题描述

我的任务是使用 ng-bootstrap 设计一个 Angular 6 沙箱。那部分进展顺利。现在我正在尝试安装旋转木马,但我正在撞墙。我正在使用 ng-bootstrap 轮播,因为我认为这可能是最好的选择,但欢迎任何其他建议,例如“纯 JavaScript”轮播。

注意,这是我的设置:

Angular CLI:6.0.7 节点:10.3.0 操作系统:darwin x64

我找到了 ng 安装说明:

https://ng-bootstrap.github.io/#/getting-started

但似乎我需要说明更多的事情。第一部分工作:

npm install --save @ng-bootstrap/ng-bootstrap

但是下一部分让我失望了:

剩下的唯一部分是列出根模块中导入的模块以及使用此库中组件的任何其他应用程序模块。对于根(顶级)模块,确切的方法会略有不同,您最终应该得到类似于(注意 NgbModule.forRoot())的代码:

什么是“根模块”?我假设那将是 app.module.ts。所以我将新代码添加到 app.module.ts 中:

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
@NgModule({
  declarations: [AppComponent, ...],
  imports: [NgbModule.forRoot(), ...],
  bootstrap: [AppComponent]
})
export class AppModule {
}

而且我看到还有另一个版本的代码可以添加到除根以外的所有模块。那里没问题。我检查了我的网站,它仍然有效。

注意,我还假设我不需要对 app.component.ts 做任何事情,对吗?我最初认为我需要向其中添加导入:

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

它并没有破坏该站点,尽管我认为不需要它,因此我将其删除。

所以,app.module.ts 应该很好用。接下来,添加示例页面上的实际轮播代码:

https://ng-bootstrap.github.io/#/components/carousel/examples

现在,我不知道进行准系统测试的最佳方法。我应该使用核心模块和/或组件作为我的组件吗?或者我应该生成一个新组件?我看到了一个向 Angular 5 添加轮播的教程,它只是将代码添加到核心模块/组件中,这就是我现在正在尝试的。会不会是个大错误?请告诉我。

无论如何,如果我将 carousel-basic.html 添加到 appl.component.html,并将 carousel-basic.ts 添加到 app.component.ts,我会出错。具体来说,

./src/app/app.module.ts
Module not found: Error: Can't resolve './carousel-basic.html'

如果我将路径更改为 ./component.html 它没有帮助。

所以真的在这一点上,我错过了一些基本的东西,但很难提出正确的问题。

有人可以指点我一些指导吗?

谢谢

标签: angularcarouselng-bootstrap

解决方案


(1)最好添加一个新的component.ts文件(代码如下)

import { Component, OnInit } from '@angular/core';
import { NgbCarouselConfig } from '@ng-bootstrap/ng-bootstrap';

@Component({
selector: 'app-slider',
templateUrl: './slider.component.html',
styles: ['']
})

export class SliderComponent implements OnInit {

images = ['https://www.akberiqbal.com/AkberIqbal.jpg', 'https://www.akberiqbal.com/AkberIqbal-og.jpg' ,'https://www.akberiqbal.com/AkberIqbal.jpg', 'https://www.akberiqbal.com/AkberIqbal-og.jpg']

constructor(private config: NgbCarouselConfig) {
  // customize default values of carousels used by this component tree
  this.config.interval = 10000;
  this.config.wrap = false;
  this.config.keyboard = false;
  this.config.pauseOnHover = false;
}

ngOnInit(): void { }

}

(2) 将 HTML 插入到 component.html 中(来自https://ng-bootstrap.github.io/#/components/carousel/examples

(3) 在你的 app.component.ts 中,添加

(4) 在您正在工作的文件夹中...

npm install bootstrap@4

(5) 进入 index.html 并添加

您的代码应该按预期工作...


推荐阅读