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.
-
Import the input() function
This step imports the
input()
function into the class.In the code editor:
- Navigate to
src/app/housing-location/housing-location.ts
- Update the file imports to include
input
andHousingLocation
: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>();}
- Navigate to
-
Add the Input property
In the same file, add a property called
housingLocation
and initialize it usinginput.required()
with the typeHousingLocationInfo
. 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
afterinput
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.Save your changes and confirm the app does not have any errors.
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.