angular - 如何在 Angular 11 组件 TS 中使用 Bootstrap 5 JS

标签 angular typescript twitter-bootstrap npm bootstrap-5

我正在开发一个使用 Angular 11 的项目,我们想使用 Bootstrap 5 原生 JS,没有第三方,如 ng-bootstrap、MDB 或 ngx-bootstrap(我们也没有使用 jQuery)。我知道在 TS 上使用 JS 库并不理想。
问题是如何导入 Bootstrap JS 并在 Angular 的 TS 组件中使用它的对象和方法。
最初我认为安装以下软件包就足够了:

npm i bootstrap@next
npm i @types/bootstrap
两者都已导入 package.json并在 node_modules 中可用.我还导入了"scripts": [ "node_modules/bootstrap/dist/js/bootstrap.js" ] angular.json 内部,但我仍然无法使用它们。
例如,如果我这样做:
import { Carousel } from 'bootstrap';
...
carousel: Carousel | any;
...
this.carousel = document.getElementById('video-carousel')
this.carousel.interval = false;
在哪里 'bootstrap' '@types/Bootstrap' .旋转木马不应该自动循环,但它会。这发生在所有其他 Bootstrap 类型中。

最佳答案

我认为您使用轮播元素的方式有点错误。为了使用轮播方法,您应该初始化 Carousel具有适当配置的元素。
而是选择代表您应该创建的轮播的原生 HTML 元素 new Carousel(elementRef, config)并通过引用类进行任何进一步的更改。

<div #carouselExampleSlidesOnly class="carousel slide">
  <div class="carousel-inner">
    <div class="carousel-item red active">
      Text 1
    </div>
    <div class="carousel-item orange">
      Text 2
    </div>
    <div class="carousel-item blue">
      Text 3
    </div>
  </div>
</div>

...
 @ViewChild("carouselExampleSlidesOnly") carouselElement: ElementRef<
    HTMLElement
  >;
  carouselRef: Carousel;
...
  ngAfterViewInit() {
    this.carouselRef = new Carousel(this.carouselElement.nativeElement, {
      slide: false
    });
  }
...
这将创建一个不会自动滑动的轮播元素。
这是一个有效的Stackblitz例如,您可以暂停和播放轮播,请记住,除了导入 node_modules/bootstrap/dist/js/bootstrap.jsscripts在您的angular.json 内您还应该导入 "./node_modules/bootstrap/dist/css/bootstrap.css"styles .

关于angular - 如何在 Angular 11 组件 TS 中使用 Bootstrap 5 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66657201/

相关文章:

angular - Mat Select 出现在页面底部

angular - 如果用户已经在 Angular 4 中登录,如何限制对登录路由的访问?

node.js - 在 NodeJS 项目中使用 TypeScript 中的路径

html - 缩小尺寸时防止 Bootstrap 中列的换行/堆叠?

jquery - Wordpress Bootstrap 主题响应式下拉菜单

javascript - 如何在 Gatsby 网站中添加 bootstrap js

javascript - Angular 2 : How do I toggle classes on similar elements

javascript - 插入一个变量作为组件模板的内联样式参数?

TypeScript:测试条件类型相等性 - 理解语法

mysql - Angular,从 mySql 数据库中存储的电子邮件验证用户