pd farhad pd farhad - 1 year ago 51
jQuery Question

Decrease Jquery use in Angular 2

This is a method in my Angular 2 component. I use TypeScript to write my Angular 2 modules. As the code shown below - I am using Jquery to access the dom level. Is it a good practice to do in Angular 2 ? Can anyone please describe the trade offs of using jquery inside Angular 2. What is the alternate way to achieve this code snippet. Code example will be appreciable , as I am a noob Angular 2 developer :)

declare var $:any;
showhidePreviousButton() {
if($('#analysisTabs').find('ul.nav-tabs > .active').prev('li').length < 1) {
else {

I am doing dynamic tab creation in my angular 2 project . Here my code is hiding "previous button" if there is only one tab, and it shows if there is more than one tab.

Answer Source

Direct DOM access is discouraged in Angular2 because it might prevent utilizing Angulars WebWorker and server-side rendering features.

It is also working against Angulars approach in general. Your code should only modify the model (or controller state) and Angular does the DOM update depending on the model.

I don't know what your code example actually tries to accomplish but I guess it would be something like

  selector: '...',
  template: `
<button [hidden]="tabs.length <= 1" (click)="prev()">prev</button><button (click)="next()">next</button>
<my-tab *ngFor="let tab of tabs" 
  [hidden]="tab !== selectedTab" 
  [class.active]="tab !== selectedTab">{{tab}}</my-tab>`
export class MyComponent {
  tabs = ['tab1', 'tab2', 'tab3'];
  constructor() {
    this.selectedTab = tabs[0];

  prev() {
    var curr = this.tabs.indexOf(this.selectedTab);
    if(curr > 0) this.selectedTab = this.tabs[curr -1];

  next() {
    var curr = this.tabs.indexOf(this.selectedTab);
    if(curr < this.tabs.lenght - 1) this.selectedTab = this.tabs[curr +1];