Components define areas of responsibility in your UI that let you reuse these sets of UI functionality.
A component is comprised of three things:
- A component class, which handles data and functionality. In the previous section, the product data and the share() method were defined for you in the component class.
- An HTML template, which determines what is presented to the user. In the previous section, you modified the product list's HTML template to display the name, description, and a "Share" button for each product.
- Component-specific styles that define the look and feel. The product list does not define any styles.
An Angular application is composed of a tree of components, in which each Angular component has a specific purpose and responsibility.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-product-alerts',
templateUrl: './product-alerts.component.html',
styleUrls: ['./product-alerts.component.css']
})
export class ProductAlertsComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
- Notice the @Component decorator. This indicates that the following class is a component. It provides metadata about the component, including its templates, styles, and a selector.
- The selector is used to identify the component. The selector is the name you give the Angular component when it is rendered as an HTML element on the page. By convention, Angular component selectors begin with the prefix app-, followed by the component name.
- The template and style filenames. These reference the other two files generated for you.
- The component definition also includes an exported class (ProductAlertsComponent), which handles functionality for the component.
- Set up the new product alerts component to receive a product as input:
- Import Input from @angular/core.
import { Component, OnInit } from '@angular/core';
import { Input } from '@angular/core';
- In the ProductAlertsComponent class definition, define a property named product with an @Input decorator. The @Input decorator indicates that the property value will be passed in from the component's parent (in this case, the product list component).
export class ProductAlertsComponent implements OnInit {
@Input() product;
constructor() { }
ngOnInit() {
}
}
- Import Output and EventEmitter from @angular/core:
import { Component } from '@angular/core';
import { Input } from '@angular/core';
import { Output, EventEmitter } from '@angular/core';
- In the component class, define a property named notify with an @Output decorator and an instance of event emitter. This makes it possible for the product alert component to emit an event when the value of the notify property changes.
export class ProductAlertsComponent {
@Input() product;
@Output() notify = new EventEmitter();
}