3

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
7
  • I don't know Materialize. Why do you think the element has a Materialize property? Commented Jan 12, 2016 at 17:23
  • Because I imported the materialize.min.js into the index.html file, is it wrong? Commented Jan 12, 2016 at 17:24
  • From the docs it looks like just Materialize.toast('toast content', 3000); should do it Commented Jan 12, 2016 at 17:27
  • it gives me a compilation error on the Atom IDE when I try that Commented Jan 12, 2016 at 17:34
  • What does the error say? Commented Jan 12, 2016 at 17:36

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Would it be better to put the jQuery call in ngAfterViewInit()?
Thanks guys, but in this special case it aint working, I am updating the question with more details ok?
Edited with more details

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.