Making Pages Interactive
Introduction: Bringing the Page to Life with Angular
Welcome back! In the last lesson, you built the main template for your Cooking Helper landing page using Angular. You set up sections for searching recipes, displaying results, showing popular recipes, and a random recipe feature — all using Angular’s component and template system.
In this lesson, you will learn how to use TypeScript within your Angular component to make your landing page interactive. By the end, you will be able to:
- Capture user input from the search form and display matching recipes
- Automatically show popular recipes when the page loads
- Add a “Surprise Me” button that fetches a random recipe
- Handle errors and give helpful feedback to users
Let’s get started and bring your Cooking Helper to life with Angular!
Quick Recall: Connecting TypeScript to Your Angular Template
Before we dive in, let’s quickly review how Angular connects your TypeScript logic to your HTML template. In Angular, each component consists of:
- A TypeScript file (e.g.,
home.component.ts) that contains the logic and data for your page - An HTML template (e.g.,
home.component.html) that defines the structure and layout - Optionally, a CSS file for styling
Angular automatically links your component’s TypeScript class to its template. Any properties or methods you define in the TypeScript file can be used in the template using Angular’s binding syntax. There’s no need for <script> tags or manual DOM manipulation.
This is the current file structure:
Now, let’s see how we can use Angular and TypeScript to make your page interactive.
Handling Recipe Search by Ingredients
The first feature we’ll add is searching for recipes by ingredients. We want users to type ingredients into a form, submit it, and see matching recipes.
Step 1: Getting the User’s Ingredients
Inside the onSearch() method in your TypeScript file, you can access the user’s input directly from the form control:
event?.preventDefault()stops the page from refreshing when submitting the form.this.searchControl.value.trim()gets the text from the input and removes extra spaces.- The string is split by commas, each ingredient is trimmed, and empty items are filtered out.
