Angular2中使用Semantic UI - 如何在组件中通过jQuery设置侧边栏的设置?

4

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

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

index.htmlhead 中导入 js 文件或在组件模板内写入 <script> 标签都无法正常工作。是否有一种 "typescript 方式" 来实现,或者如何在组件内部使用 js 文件?


使用 webpack 还是 systemjs? - anshuVersatile
我使用angular-cli创建了这个项目,直到你问我之前我才没有想过这个问题。现在我看了一下,发现既没有system.js也没有webpack.config.js。 - Bünyamin Sarıgül
3个回答

4

我找到了这个链接,关于在指令中使用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>

1
我花了相当长的时间来让这个工作,尽管最终很简单。希望能为您节省一些时间...
无需创建指令,您可以像使用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 上运行。

0
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') ;
  }
}

我收到了 "模块构建失败:错误:/home/bunyamin/WebstormProjects/C3DP/src/app/app.component.ts(11,22):类型'ElementFinder'上不存在属性'sidebar'。)" 的错误信息。 - Bünyamin Sarıgül
你是如何添加 jQuery 的? - anshuVersatile
webpack 还是 systemjs? - anshuVersatile
我没有使用ng-semantic,只是使用了semantic.css和js文件。 - Bünyamin Sarıgül
你对此有什么进展吗?我也遇到了同样的问题。ng-semantic不完整,缺少许多语义化组件,所以我正在尝试使用标准的语义化UI CSS和JS。 - pieperu
ng-semantic针对Angular2的开发仍在进行中,因此需要等待一段时间。 - anshuVersatile

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接