带有bootstrap 4事件的Angular 5不会触发

时间:2018-03-06 08:25:03

标签: angular bootstrap-4

在Angular Component上调用bootstrap collapse事件时遇到问题。 Angular 5 with cli。

问题是在component.ts中没有拾取bootstrap collapse事件 https://getbootstrap.com/docs/4.0/components/collapse/

hide.bs.collapse无法触发,jquery中的正常事件就像点击一样可以触发。

导入bootstrap javascript的方式是否有问题或者该事件无法在角度5中使用?

angular-cli(片段)

  "styles": [
    "styles.scss",
    "../node_modules/bootstrap/dist/css/bootstrap.min.css",
    "../node_modules/font-awesome/scss/font-awesome.scss"
  ],
  "scripts": [
    "../node_modules/jquery/dist/jquery.min.js",
    "../node_modules/popper.js/dist/umd/popper.min.js",
    "../node_modules/bootstrap/dist/js/bootstrap.min.js"
  ],

app.module.ts(整个代码)

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AngularFontAwesomeModule } from 'angular-font-awesome';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';


@NgModule({
  declarations: [
    AppComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AngularFontAwesomeModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

home.component.ts(片断)

import { Component, OnInit} from '@angular/core';
import * as $ from 'jquery';
import { Subject } from '../model/subject';
import { Education } from '../model/education';
import { Biodata } from '../model/biodata';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'] 
})

export class HomeComponent implements OnInit {

  educations: Education[];
  biodata: Biodata;
  stringEdus: string;

  constructor() { }

  ngOnInit() {
    this.initializeEducation();
    this.initializeBiodata();

    console.log(this.educations);
    console.log(this.biodata);

    $(document).ready(function(){
      $('.collapse').on('hide.bs.collapse', function () {
        // do something…
        console.log('abc123');
      });
    });
  }

更新

我使用ngBootstrap进行我想要的更改。

1 个答案:

答案 0 :(得分:0)

尝试将该事件订阅放在ngAfterViewInit()方法而不是ngOnInit()中。

import { Component, OnInit, AfterViewInit } from '@angular/core';
...
export class HomeComponent implements OnInit, AfterViewInit {
  ...
  ngAfterViewInit() {
    $('.collapse').on(...);
  }
}

Btw filipbarak是对的。你不应该将角度2和jquery混合在一起。