Angular 2 getting an element in angular 2 for use in Material design lite

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); //prints undefined //snackbarContainer.MaterialSnackbar.showSnackbar(data); } 

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?

+5
source share
3 answers

I solved the problem by putting the code in ngAfterViewInit() , and also calling upgradeElement as shown below:

 constructor(private el:ElementRef){} ngAfterViewInit(){ window.componentHandler.upgradeAllRegistered(); var snackbarContainer = this.el.nativeElement.querySelector("#toast_error") var data = { message: 'Button color changed.', timeout: 2000, actionText: 'Undo' }; snackbarContainer.MaterialSnackbar.showSnackbar(data); } 
+3
source

If you need direct access to the DOM element, enter ElementRef :

 constructor(ref: ElementRef) ... 

And then go into the DOM element using:

 ref.nativeElement 

See here for more details.

Then, instead of OnInit try with AfterViewInit to make sure that the DOM is initialized before running the DOM request - see here .

+2
source

You can use the template variables and @ViewChild to get a specific element:

 <div id="toast_error" #toastError> Error message </div> @ViewChile('toastError') toastErrorDiv; ngAfterViewInit() { toastErrorDiv.doSomething(); } 
0
source

Source: https://habr.com/ru/post/1243730/


All Articles