Last active
October 2, 2016 15:23
-
-
Save robsilva/2177b657f3dfc5300ece09ad6a7b81ac to your computer and use it in GitHub Desktop.
Raising custom events in Angular 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// index.html | |
<!doctype html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>App</title> | |
<base href="/"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<link rel="icon" type="image/x-icon" href="favicon.ico"> | |
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/css/bootstrap.min.css"> | |
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.css"> | |
</head> | |
<body> | |
<app-root>Loading...</app-root> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script> | |
<script src="//cdnjs.cloudflare.com/ajax/libs/tether/1.2.0/js/tether.min.js"></script> | |
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/js/bootstrap.min.js"></script> | |
</body> | |
</html> | |
// favorite.component.ts | |
import { Component, Input, Output, EventEmitter } from '@angular/core'; | |
@Component({ | |
selector: 'app-favorite', | |
templateUrl: './favorite.component.html', | |
styleUrls: ['./favorite.component.css'] | |
}) | |
export class FavoriteComponent { | |
@Input() isFavorite = false; | |
@Output() change = new EventEmitter(); | |
onClick() { | |
this.isFavorite = !this.isFavorite; | |
this.change.emit({ newValue: this.isFavorite }) | |
} | |
} | |
// favorite.component.html | |
<p> | |
<i class="fa" | |
[class.fa-star-o]="!isFavorite" | |
[class.fa-star]="isFavorite" | |
(click)="onClick()" | |
></i> | |
</p> | |
// app.component.ts | |
import { Component } from '@angular/core'; | |
@Component({ | |
selector: 'app-root', | |
templateUrl: './app.component.html', | |
styleUrls: ['./app.component.css'] | |
}) | |
export class AppComponent { | |
title = 'app works!'; | |
onFavoriteChange($event) { | |
console.log($event); | |
} | |
} | |
// app.component.html | |
<h1> | |
{{title}} | |
</h1> | |
<app-favorite (change)="onFavoriteChange($event)"></app-favorite> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment