Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Jquery Method inside Component Angular 2

Tags:

jquery

angular

I need to call a Jquery method inside an angular component, this is the scenario:

I want to use Materialize CSS framework toast feature:

eg:

Materialize.toast('toast content', 3000);

I tried to do like that:

ngAfterViewInit() {
  $(this.elementRef.nativeElement.Materialize.toast('toast content', 3000));
}

My console output is:

TypeError: Cannot read property 'toast' of undefined
like image 528
Marcos J.C Kichel Avatar asked Jun 14 '26 02:06

Marcos J.C Kichel


1 Answers

If you must

class MyComponent implements AfterViewInit {
  constructor(private _elementRef: ElementRef) {
  }
  ngAfterViewInit() {
    $(this._elementRef.nativeElement)...
  }
}

You might also need to disable view encapsulation

@Component({
  selector: 'zippy',
  templateUrl: 'zippy.html',
  styles: [`
    .zippy {
      background: green;
    }
  `],
  encapsulation: ViewEncapsulation.None
})

For more details see http://blog.thoughtram.io/angular/2015/06/29/shadow-dom-strategies-in-angular2.html

You should be aware that direct DOM access is discouraged in Angular2 because it prevents running in web worker and server rendering. Also issues with are to be expected using jQuery.

like image 124
Günter Zöchbauer Avatar answered Jun 15 '26 23:06

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!