home

Examples

Input - Output with EventEmitter

hero-list-component.ts

import {Component, OnInit} from '@angular/core';
import {Hero, HEROES} from '../model/Hero';

@Component({
    selector: 'app-hero-list',
    templateUrl: './hero-list.component.html',
    styleUrls: ['./hero-list.component.css']
})
export class HeroListComponent {
    HEROES = HEROES;
    selectedHero : Hero;
    constructor() {}
}

hero-list-component.html

<ul>
    <li *ngFor="let hero of HEROES" (click)="selectedHero = hero">
        {{hero.id}} - {{hero.name}}
    </li>
</ul>
<app-hero-detail *ngIf="selectedHero"
                 [hero]="selectedHero"
                 (closeEmitter)="selectedHero = null">
</app-hero-detail>

hero-detail-component.ts

import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {Hero} from '../model/Hero';

@Component({
    selector: 'app-hero-detail',
    templateUrl: './hero-detail.component.html',
    styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {
    @Input()
    hero: Hero;

    @Output()
    closeEmitter: EventEmitter<any> = new EventEmitter();

    constructor() {}

    ngOnInit() {}

    emitClose(event) {
        this.closeEmitter.emit(event);
    }
}

hero-detail-component.html

<div>
    <input [(ngModel)]="hero.name">
    <button (click)="emitClose()">Close!</button>
</div>