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

问题描述 投票:1回答:1

我在Angular Component上调用bootstrap collapse事件时遇到了问题。角度5与cli。

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

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

是导入bootstrap javascript的方式有问题还是事件不能在angular 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来进行我想要的更改。

angular bootstrap-4
1个回答
0
投票

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

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

Btw filipbarak是对的。你不应该将角度2与jquery混合。

© www.soinside.com 2019 - 2024. All rights reserved.