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 HousingLocationComponent
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 @Input()
properties in the HousingLocationComponent
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 decorator
This step imports the
Input
decorator into the class.In the code editor:
- Navigate to
src/app/housing-location/housing-location.component.ts
- Update the file imports to include
Input
andHousingLocation
:Import HousingLocationComponent and Input in src/app/housing-location/housing-location.component.ts
import {Component, Input} from '@angular/core';import {CommonModule} from '@angular/common';import {HousingLocation} from '../housinglocation';@Component({ selector: 'app-housing-location', standalone: true, imports: [CommonModule], template: ` <p>housing-location works!</p> `, styleUrls: ['./housing-location.component.css'],})export class HousingLocationComponent { @Input() housingLocation!: HousingLocation;}
- Navigate to
-
Add the Input property
In the same file, add a property called
housingLocation
of typeHousingLocation
to theHousingLocationComponent
class. Add an!
after the property name and prefix it with the@Input()
decorator:Import HousingLocationComponent and Input in src/app/housing-location/housing-location.component.ts
import {Component, Input} from '@angular/core';import {CommonModule} from '@angular/common';import {HousingLocation} from '../housinglocation';@Component({ selector: 'app-housing-location', standalone: true, imports: [CommonModule], template: ` <p>housing-location works!</p> `, styleUrls: ['./housing-location.component.css'],})export class HousingLocationComponent { @Input() housingLocation!: HousingLocation;}
You have to add the
!
because the input is expecting the value to be passed. In this case, there is no default value. In our example application case we know that the value will be passed in - this is by design. The exclamation point is called the non-null assertion operator and it tells the TypeScript compiler that the value of this property won't be null or undefined.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 property decorated with the @Input()
decorator. You also used the non-null assertion operator to notify the compiler that the value of the new property won't be null
or undefined
.