I want to use Material Design Lite eatery in Angular 2.
I tried to take hold of an element in my template as follows:
My template
<test> <div id="child1"> child1 <div id="child2"> <div id="child2"> child2 <div id="child2"> <div id="toast_error"> Error message </div> </div> </div> </div> </test>
In my component file
constructor(private el:ElementRef){} ngOnInit(){ this.show_error("something"); } show_error(err){ var snackbarContainer = this.el.nativeElement.querySelector("#toast_error") var data = { message: 'Button color changed.', timeout: 2000, actionText: 'Undo' }; snackbarContainer.MaterialSnackbar.showSnackbar(data); }
I get the following error message. How to get an element with id toast_error
EXCEPTION: TypeError: Cannot read property 'MaterialSnackbar' of null in [null]
PS: I checked that this.el.nativeElement gives me the correct link
Edit
Following the answers and comments, I can now get the element using the same code inside ngAfterViewInit . However, I cannot get the diner to work. Below is the updated code.
In my component file
constructor(private el:ElementRef){} ngAfterViewInit(){ var snackbarContainer = this.el.nativeElement.querySelector("#toast_error") var data = { message: 'Button color changed.', timeout: 2000, actionText: 'Undo' }; console.log(snackbarContainer.MaterialSnackbar);
The console.log() command prints undefined. I made sure that material.min.js is uploaded and checked the file, it includes MaterialSnackbar . How do I debug this?
source share