17.10.2018 Views

Angular

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 12: Directives & components :<br />

@Input @Output<br />

Section 12.1: <strong>Angular</strong> 2 @Input and @Output in a nested<br />

component<br />

A Button directive which accepts an @Input() to specify a click limit until the button gets disabled. The parent<br />

component can listen to an event which will be emitted when the click limit is reached via @Output:<br />

import { Component, Input, Output, EventEmitter } from '@angular/core';<br />

@Component({<br />

selector: 'limited-button',<br />

template: `<br />

<br />

`,<br />

directives: []<br />

})<br />

export class LimitedButton {<br />

@Input() clickLimit: number;<br />

@Output() limitReached: EventEmitter = new EventEmitter();<br />

disabled: boolean = false;<br />

private clickCount: number = 0;<br />

}<br />

onClick() {<br />

this.clickCount++;<br />

if (this.clickCount === this.clickLimit) {<br />

this.disabled = true;<br />

this.limitReached.emit(this.clickCount);<br />

}<br />

}<br />

Parent component which uses the Button directive and alerts a message when the click limit is reached:<br />

import { Component } from '@angular/core';<br />

import { LimitedButton } from './limited-button.component';<br />

@Component({<br />

selector: 'my-parent-component',<br />

template: `<br />

You can only click me twice<br />

`,<br />

directives: [LimitedButton]<br />

})<br />

export class MyParentComponent {<br />

onLimitReached(clickCount: number) {<br />

alert('Button disabled after ' + clickCount + ' clicks.');<br />

}<br />

}<br />

GoalKicker.com – <strong>Angular</strong> 2 Notes for Professionals 63

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!