The @Input decorator is used when a component is supposed to receive data passed down from its parent. When a field or property is set as input, the parent can specify the value via standard assignment.
Let's use input in the category menu-related components:
- Create the relevant model representations:
- Create a folder at src/app/model.
- Create a file, category.ts, in the new model folder, with the following content:
export interface Category {
name: string;
}
- Use the re-export strategy to aggregate all model representations by creating a file called index.ts in the model folder with the following content:
export * from './category';
- Open category-menu.component.ts and add the categories field as input:
import { Component, Input } from '@angular/core';
import { Category } from '../../../model';
@Component({
selector: 'app-category-menu',
templateUrl: './category-menu.component.html',
styleUrls: ['./category-menu.component.css']
})
export class CategoryMenuComponent {
@Input() categories: Category[];
}
- Open the parent products-page.component.ts component file and initialize categories with hardcoded values:
import { Component, OnInit } from '@angular/core';
import { Category } from '../../../model';
@Component({
selector: 'app-products-page',
templateUrl: './products-page.component.html',
styleUrls: ['./products-page.component.css']
})
export class ProductsPageComponent implements OnInit {
categories: Category[] = [
{name: 'Books'},
{name: 'Appliances'},
{name: 'Food'},
];
constructor() { }
ngOnInit() {
}
}
- In products-page.component.html, pass down the hardcoded categories to the child's categories input by using property binding:
<app-category-menu [categories]="categories"></app-category-menu>
- The categories should now be available to the CategoryMenuComponent as passed-down input.
- Before using the categories to generate the menu items, enable CategoryMenuItemComponent to receive the category name as input:
- In category-menu-item.component.ts, add a categoryName field as input:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-category-menu-item',
templateUrl: './category-menu-item.component.html',
styleUrls: ['./category-menu-item.component.css']
})
export class CategoryMenuItemComponent {
@Input() categoryName: string;
}
- In category-menu-item.component.html, bind the field categoryName state with interpolation binding:
<div class="container">
<span>{{ categoryName }}</span>
</div>
- Replace the entire contents of category-menu.component.html and bind the component's field categories to generate the menu items:
<ul>
<li *ngFor="let c of categories">
<app-category-menu-item [categoryName]="c.name">
</app-category-menu-item>
</li>
</ul>
You can now run the application and see the generated menu items generated according to the hardcoded state you initialized.