Bünyamin Sarıgül Bünyamin Sarıgül - 3 years ago 213
Javascript Question

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

I have an Angular2 application and I want to use

Semantic UI
. However, there are some
jQuery
configurations like below that I have to run after a component loaded:

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


It is not working by importing the js file in the
head
of
index.html
or writing it in a
<script>
tag inside of a component template. Is there a "
typescript
way" to do that or how can I use a js file inside of a component?

Answer Source

I found this link about using jQuery in directives, then I created a sidebar directive:

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() {

  }

}

Then, I used it in the template:

<div id="app">
    <div context="#app" class="ui left vertical menu sidebar"></div>
    <div class="pusher"></div>
</div>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download