Tuesday, 29 May 2018

Angular - Component Interaction

This cookbook contains recipes for common component communication scenarios in which two or more components share information.
Pass data from parent to child with input binding:
HeroChildComponent has two input properties, typically adorned with @Input decorations.
component-interaction/src/app/hero-child.component.ts
import { Component, Input } from '@angular/core';

import { Hero } from './hero';

  selector: 'app-hero-child',
  template: `
    <h3>{{hero.name}} says:</h3>
    <p>I, {{hero.name}}, am at your service, {{masterName}}.</p>
  `
})
export class HeroChildComponent {
  @Input() hero: Hero;
  @Input('master') masterName: string;
}
The second @Input aliases the child component property name masterName as 'master'.
The HeroParentComponent nests the child HeroChildComponent inside an *ngFor repeater, binding its master string property to the child's master alias, and each iteration's hero instance to the child's hero property.
component-interaction/src/app/hero-parent.component.ts
import { Component } from '@angular/core';

import { HEROES } from './hero';

  selector: 'app-hero-parent',
  template: `
    <h2>{{master}} controls {{heroes.length}} heroes</h2>
    <app-hero-child *ngFor="let hero of heroes"
      [hero]="hero"
      [master]="master">
    </app-hero-child>
  `
})
export class HeroParentComponent {
  heroes = HEROES;
  master = 'Master';
}
The running application displays three heroes:





















No comments:

Post a Comment