Add an input parameter to the component

This tutorial lesson demonstrates how to create a component input and use it to pass data to a component for customization.

What you'll learn

Your app's HousingLocation template has a HousingLocation property to receive input.

Conceptual preview of Inputs

Inputs allow components to share data. The direction of the data sharing is from parent component to child component.

In this lesson, you'll define an input property in the HousingLocation component which will enable you to customize the data displayed in the component.

Learn more in the Accepting data with input properties and Custom events with outputs guides.

  1. Import the input() function

    This step imports the input() function into the class.

    In the code editor:

    1. Navigate to src/app/housing-location/housing-location.ts
    2. Update the file imports to include input and HousingLocation:

      Import HousingLocation and Input in src/app/housing-location/housing-location.ts

            
      import {Component, input} from '@angular/core';import {HousingLocationInfo} from '../housinglocation';@Component({  selector: 'app-housing-location',  imports: [],  template: `    <p>housing-location works!</p>  `,  styleUrls: ['./housing-location.css'],})export class HousingLocation {  housingLocation = input.required<HousingLocationInfo>();}
  2. Add the Input property

    1. In the same file, add a property called housingLocation and initialize it using input.required() with the type HousingLocationInfo. To set the type, use a generic parameter, by writing <HousingLocationInfo> immediately after .required:

      Import HousingLocation and Input in src/app/housing-location/housing-location.ts

            
      import {Component, input} from '@angular/core';import {HousingLocationInfo} from '../housinglocation';@Component({  selector: 'app-housing-location',  imports: [],  template: `    <p>housing-location works!</p>  `,  styleUrls: ['./housing-location.css'],})export class HousingLocation {  housingLocation = input.required<HousingLocationInfo>();}

      You have to add .required after input to indicate that the parent component must provide a value. In our example application, we know this value will always be passed in — this is by design. The .required() call ensures that the TypeScript compiler enforces this and treats the property as non-nullable when this component is used in a template.

    2. Save your changes and confirm the app does not have any errors.

    3. Correct any errors before you continue to the next step.

SUMMARY: In this lesson, you created a new input property. You also used the .required method to ensure the signal value is always defined.