簡體   English   中英

Angular - 如何將 Javascript 導入 Angular 組件

[英]Angular - How to import Javascript into Angular Component

在我的 Angular-11 中,我有這個 Javascript 文件:

“node_modules/admin-lte/plugins/bs-stepper/js/bs-stepper.min.js”,

如上所示,我將其添加到 angular.json 中。

 import Stepper from '...'; @Component({ selector: 'app-profile', templateUrl: './profile.component.html', styleUrls: ['./profile.component.css'] }) export class ProfileComponent implements OnInit { name = 'Angular'; private stepper: Stepper; next() { this.stepper.next(); } onSubmit() { return false; } ngOnInit() { this.stepper = new Stepper(document.querySelector('#stepper1'), { linear: false, animation: true }) } }

我如何將它導入到這個組件中:profile.component.ts 這種方式,

從'...'導入步進器;

從 Javascript 路徑

謝謝

您必須首先在 typing.d.ts 中聲明它並包含 angular.json 腳本。

在 angular.json

{
  "build" : {
      "scripts" : [
           "node_modules/admin-lte/plugins/bs-stepper/js/bs-stepper.min.js",
           ....
       ]        

在打字.d.ts

declare module 'admin-lte/plugins/bs-stepper/js/bs-stepper.min';

注意:如果這是 JQuery package 那么您需要創建一個接口。

declare module 'jquery';
interface JQuery { 
  Stepper(DOM : any, options?: any): any;
}

最后,您現在可以在組件中調用它。

在組件中

import Stepper from 'admin-lte/plugins/bs-stepper/js/bs-stepper.min';

編輯:在 src 文件夾中創建一個名為typing.d.ts的文件。 然后加

/// <reference path = "typings.d.ts" />

src/main.ts文件的頂部

碰巧有一個用於bs-stepper的 NPM package 可以與 Angular 一起使用。

1.安裝package

從項目根文件夾中,運行命令

npm install bs-stepper --save

如果需要,還安裝bootstrap

npm install bootstrap --save

2.導入CSS

styles.css

@import '~bs-stepper/dist/css/bs-stepper.min.css';

/* Also import bootstrap if needed */
@import '~bs-stepper/dist/css/bs-stepper.min.css';

3. 使用ViewChild代替querySelector

在 Angular 應用程序中使用document.querySelector將搜索整個 DOM,而元素只會出現在當前組件中。 根據應用程序的大小,它可能會導致性能問題。 相反,您可以將@ViewChild裝飾器與模板引用變量一起使用

模板 (*.html)

<!-- Here, `bsStepper` is the template reference variable -->

<div #bsStepper id="stepper1" class="bs-stepper">
  ...
</div>

組件 (*.ts)

import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import Stepper from 'bs-stepper';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  @ViewChild('bsStepper', { static: false }) stepperElement!: ElementRef<any>;
  public stepper!: Stepper;

  next() {
    this.stepper.next();
  }

  onSubmit() {
    return false;
  }

  ngAfterViewInit() {
    this.stepper = new Stepper(this.stepperElement.nativeElement, {
      linear: false,
      animation: true
    });
  }
}

工作示例: Stackblitz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM