You have unlimited access as a PRO member
You are receiving a free preview of 3 lessons
Your free preview as expired - please upgrade to PRO
Contents
Recent Posts
- Object Oriented Programming With TypeScript
- Angular Elements Advanced Techniques
- TypeScript - the Basics
- The Real State of JavaScript 2018
- Cloud Scheduler for Firebase Functions
- Testing Firestore Security Rules With the Emulator
- How to Use Git and Github
- Infinite Virtual Scroll With the Angular CDK
- Build a Group Chat With Firestore
- Async Await Pro Tips
Using ViewChild in Ionic 4 to Call Component Methods
written by Jeff DelaneyMany of Ionic’s components expose API methods for building custom behaviors. But how do you access these API methods on a component that lives in the HTML?
The ViewChild decorator is extremely useful in Ionic v4 for grabbing elements from the DOM to call the components API methods in your TS code. Let’s use the menu component as an example. Out of the box, the only way to close it is by tapping outside of it, but you might more programmatic control over it.
Grabbing Ionic Components with ViewChild
Let’s imagine we have a HomePage
component that looks like this and we want to close the menu when an item is clicked.
<ion-menu> |
Our goal is to access the ion-menu
from the TypeScript code so we can call its API methods, like open()
and close()
.
import { Component, ViewChild } from '@angular/core'; |
Shortcut: Use Template Variables
There’s actually a very convenient shortcut to using ViewChild in a component. We never have to leave the HTML by setting a template variable in Angular. In this example we reference the menu component with a hashtag and variable name #mymenu
.
<ion-menu #mymenu> |
And we’re done. Much easier then using ViewChild in the TypeScript.
Grabbing Multiple Components with ViewChildren
You might also run into a situation where there are multiple components of the same type on the page, such as multiple FABs:
<ion-fab></ion-fab> |
ViewChildren
is almost the same, but it will grab all elements that match this component and return them as an Array.
import { Component, ViewChildren } from '@angular/core'; |
Now that you know about ViewChild
, you should have no problem accessing the API methods found on Ionic’s web components.