Angular2 的语义 UI - 如何在组件中从 jQuery 设置边栏设置?

Semantic UI with Angular2 - How to set Sidebar settings from jQuery in a component?

我有一个 Angular2 应用程序,我想使用 Semantic UI。但是,有一些 jQuery 配置如下,我必须 运行 在组件加载后:

$('#app .ui.sidebar')
    .sidebar({context:$('#app')})
    .sidebar('setting', 'transition', 'overlay') 

将 js 文件导入 index.htmlhead 或将其写入组件模板内的 <script> 标记中是行不通的。是否有“typescript 方式”来做到这一点,或者我如何在组件内部使用 js 文件?

import { Component, OnInit } from '@angular/core';
declare var $:any;
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app works!';
  ngOnInit(){
    $('#app .ui.sidebar')
    .sidebar({context:$('#app')})
    .sidebar('setting', 'transition', 'overlay') ;
  }
}

我发现 this link 关于在指令中使用 jQuery,然后我创建了一个边栏指令:

import {Directive, ElementRef, OnDestroy, OnInit, Input} from '@angular/core';
import {HostListener} from "@angular/core/src/metadata/directives";

declare var $: any

@Directive({
  selector: '.ui.sidebar'
})
export class SidebarDirective implements OnInit, OnDestroy {
  @Input() context: string;
  constructor(private el: ElementRef) {
  }

  public ngOnInit() {
    $(this.el.nativeElement)
      .sidebar({context: this.context})
      .sidebar('setting', 'transition', 'overlay');
  }

  public ngOnDestroy() {

  }

}

然后,我在模板中使用了它:

<div id="app">
    <div context="#app" class="ui left vertical menu sidebar"></div>
    <div class="pusher"></div>
</div>

虽然最后它相当简单,但我花了很多时间来让它工作。希望能为您节省一些时间...

无需创建指令,您可以像使用 JavaScript 一样使用 jQuery 命令(在 https://semantic-ui.com/modules/sidebar.html#/usage 中有描述)。但是,必须声明“$”并且命令必须位于 TypeScript 函数中 ("toggle()"):

import {Component} from '@angular/core';

declare var $: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {

  toggle() {
    $('.ui.sidebar').sidebar('toggle');
  }
}

模板的相应部分可能如下所示:

<div class="ui fixed inverted main menu">
  <a (click)="toggle()" class="launch icon item">
    <i class="content icon"></i>
    <p style="padding-left:1em">Menu</p>
  </a>
</div>

不要忘记将 jQuery 添加到 .angular-cli.json:

的脚本部分
"scripts": [
  "../node_modules/jquery/dist/jquery.js",
  "../node_modules/semantic-ui-css/semantic.min.js"
],

我正在使用 Semantic UI 2.2.12,它已经依赖于 jQuery 3.2.1。 Angular 版本是 4.4.4 运行 node.js 6.11.2.