Use of ViewChild in angular

import { ViewChild } from ‘@angular/core’;

what is use of Viewchild in angular /ionic

thanks in advance :grinning:

Sometimes you need to “get a hold of” some element on the page, so that you can set properties on it, etc. E.g., I have a page with an HTML5 <audio> element. I need to dynamically add the source of the file that needs to be played when the user clicks the play button. So, I can do this:

@ViewChild audio: any;

Now, in my code, I can do stuff like:

this.audio.setProperty('src', 'assets/EN/1.mp3')

In another case I want to programmatically scroll the page to the top. So, I have to use ViewChild to get a handle on the IonContent element so that I can call scrollToTop() on that object.

1 Like