0

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) {
            $('.prev-btn').hide();
          }
          else {
            $('.prev-btn').show();
          }
        }

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.

pd farhad
  • 6,352
  • 2
  • 28
  • 47

2 Answers2

1

I think you must go through this post before you do anything further. Everything that needs to be said has been said before, so I am merely pointing you to it. Thinking in Angular with a jQuery background

In short, try not to manipulate DOM or use jQuery when you are using angular and think in terms of design and not kludging quick-fix solutions.

Community
  • 1
  • 1
phreakv6
  • 2,135
  • 1
  • 9
  • 11
0

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

@Component({
  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'];
  selectedTab;
  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];
  }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I edited my question. Still I am accepting it because it answers my core questions. Can you please suggest me how I can do this show-hide behavior – pd farhad Jun 07 '16 at 07:01