How to Add an Input Parameter to an Angular Component

Introduction to Inputs
In Angular, @Input() properties allow components to share data. The data flow is from the parent component to the child component. In this lesson, we’ll learn how to add @Input() properties to the HousingLocationComponent to control the data it displays.

Step 1: Import the Input Decorator
To begin, you’ll need to import the Input decorator, which enables the component to accept data from its parent.

  • Open your code editor and navigate to: src/app/housing-location/housing-location.component.ts
  • Modify the import statement at the top of the file to include Input and HousingLocation:
import { Component, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HousingLocation } from '../housinglocation';

Step 2: Define the Input Property
Next, we’ll add a property to the HousingLocationComponent class, which will hold the data passed from the parent component.

  • Add the following code to your HousingLocationComponent:
export class HousingLocationComponent {
  @Input() housingLocation!: HousingLocation;
}

The @Input() decorator indicates that the housingLocation property will receive data from the parent component. The exclamation mark (!) is used as a non-null assertion operator, ensuring TypeScript that the value will be provided and won’t be null or undefined.

Step 3: Save and Test

  • Save your changes.
  • Ensure there are no errors by running the app. Fix any issues if they arise before moving on.

In this guide, you successfully added an @Input() property to the HousingLocationComponent. You also learned how to use the non-null assertion operator (!) to let the TypeScript compiler know that the housingLocation property will always be provided.

This simple change allows your Angular component to be more flexible, as it can now display dynamic data passed from a parent component

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *