Common features of Angular’s template syntax, the source code for the below is available at https://github.com/carlpaton/angular.io-start and was built using https://angular.io/start
ngFor
1 2 3 4
| product-list.component.html
<div *ngFor="let product of products"> </div>
|
1 2 3 4 5 6 7 8 9 10 11
| product-list.component.ts
import { products } from '../products'; @Component({ selector: 'app-product-list', templateUrl: './product-list.component.html', styleUrls: ['./product-list.component.css'] }) export class ProductListComponent { products = products; }
|
1 2 3 4 5 6 7
| export const products = [ { name: 'Phone XL', price: 799, description: 'A large phone with one of the best screens' } ];
|
ngIf, Interpolation { { } }
1 2 3 4 5
| product-list.component.html <p *ngIf="product.description"> Description: {{ product.description }} </p>
|
Property binding [ ]
1 2 3 4 5
| <h3> <a [title]="product.name + ' details'"> {{ product.name }} </a> </h3>
|
Event binding ( )
1 2 3 4 5
| product-list.component.html
<button (click)="share()"> Share </button>
|
1 2 3 4 5 6 7 8 9 10 11 12
| product-list.component.ts
@Component({ ... }) export class ProductListComponent { products = products;
share() { window.alert('The product has been shared hoe!'); } }
|
Here product
is created in the ngFor
loop and is an input to component app-product-alerts
1 2 3 4 5 6 7
| product-list.component.html
<div *ngFor="let product of products"> <app-product-alerts [product]="product" </app-product-alerts> </div>
|
A property named product
is defined with an @Input
decorator
1 2 3 4 5 6 7 8 9
| product-alerts.component.ts
import { Input } from '@angular/core'; @Component({ ... }) export class ProductAlertsComponent implements OnInit { @Input() product; }
|
This input can then be used in the html
1 2 3 4 5
| product-alerts.component.html
<p *ngIf="product.price > 700"> <button>Notify Me</button> </p>
|
Output
Emit an event up to the product list component from product-alerts.component
1 2 3 4 5 6 7
| product-alerts.component.ts
import { Output, EventEmitter } from '@angular/core'; export class ProductAlertsComponent { @Input() product; @Output() notify = new EventEmitter(); }
|
Event binding to call the notify.emit()
method
1 2 3 4 5
| product-alerts.component.html
<p *ngIf="product.price > 700"> <button (click)="notify.emit()">Notify Me</button> </p>
|
Behavior that should happen when the button is clicked (In the parent component product-list.component
)
1 2 3 4 5 6 7
| product-list.component.ts
export class ProductListComponent { onNotify() { window.alert('You will be notified when the product goes on sale'); } }
|
Update the product list component to receive output from the product alerts component.
1 2 3 4 5 6
| product-list.component.html
<app-product-alerts [product]="product" (notify)="onNotify()"> </app-product-alerts>
|
Reference