Skip to content Skip to sidebar Skip to footer

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.side

Solution 1:

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>

Solution 2:

I have spent quite some time to get this working although it is rather simple in the end. Hope to save you some time ...

There is no need to create a directive, you can use the jQuery command as you would use with JavaScript (described at https://semantic-ui.com/modules/sidebar.html#/usage). However, "$" has to be declared and the command has to be located in a TypeScript function ("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');
  }
}

The corresponding section of the template may look like this:

<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>

Don't forget to add jQuery to the scripts section of .angular-cli.json:

"scripts": [
  "../node_modules/jquery/dist/jquery.js",
  "../node_modules/semantic-ui-css/semantic.min.js"
],

I'm using Semantic UI 2.2.12 which already depends on jQuery 3.2.1. Angular version is 4.4.4 running on node.js 6.11.2.


Solution 3:

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

Post a Comment for "Semantic UI With Angular2 - How To Set Sidebar Settings From JQuery In A Component?"