Skip to content

Instantly share code, notes, and snippets.

@revov
Last active May 7, 2016 10:46
Show Gist options
  • Save revov/f413d63747e51975658becc03a39bf71 to your computer and use it in GitHub Desktop.
Save revov/f413d63747e51975658becc03a39bf71 to your computer and use it in GitHub Desktop.
import { Component, Input, ViewChildren } from '@angular/core';
import 'rxjs/add/operator/filter';
@Component({
selector: 'todo',
template: `
<div>{{title}}</div>
`
})
class Todo {
@Input() title;
animate() {
console.log(`Pretend ${this.title} is animating`);
}
}
@Component({
template: `
<div *ngFor="let item of items; let i = index">
<todo (click)="handleClick(i)" [title]="item"></todo>
</div>
`,
directives: [Todo]
})
export class Todos {
items = ['Apple', 'Banana', 'Cranberry'];
@ViewChildren(Todo) todoRefs;
ngAfterViewInit() {
this.todoRefs.changes
.filter( todoRefs => todoRefs.length === 1 )
.subscribe( todoRefs => todoRefs.last.animate() );
}
handleClick(index) {
this.items.splice(index, 1);
}
}
var Todo = React.createClass({
render: function() {
return <div onClick={this.props.onClick}>{this.props.title}</div>;
},
//this component will be accessed by the parent through the `ref` attribute
animate: function() {
console.log('Pretend %s is animating', this.props.title);
}
});
var Todos = React.createClass({
getInitialState: function() {
return {items: ['Apple', 'Banana', 'Cranberry']};
},
handleClick: function(index) {
var items = this.state.items.filter(function(item, i) {
return index !== i;
});
this.setState({items: items}, function() {
if (items.length === 1) {
this.refs.item0.animate();
}
}.bind(this));
},
render: function() {
return (
<div>
{this.state.items.map(function(item, i) {
var boundClick = this.handleClick.bind(this, i);
return (
<Todo onClick={boundClick} key={i} title={item} ref={'item' + i} />
);
}, this)}
</div>
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment