Skip to content

Instantly share code, notes, and snippets.

@zhentian-wan
Created March 20, 2016 17:32
Show Gist options
  • Save zhentian-wan/52a916a264af122bc806 to your computer and use it in GitHub Desktop.
Save zhentian-wan/52a916a264af122bc806 to your computer and use it in GitHub Desktop.
Angular 2 ngFor
import {Component} from 'angular2/core';
import {bootstrap} from 'angular2/bootstrap';
import {TodoService} from './TodoService';
import {TodoInput} from './TodoInput';
import {TodoList} from './TodoList';
@Component({
selector: 'app',
directives: [TodoInput, TodoList],
template: `
<todo-input></todo-input>
<todo-list></todo-list>
`
})
class App {
}
// []: we can inject service which can be used for the whole app
bootstrap(App, [
TodoService
]);
import {Component} from 'angular2/core';
import {TodoService} from './TodoService';
@Component({
selector: 'todo-input',
template: `
<div>
<input #myInput type="text">
<button (click)="onClick(myInput.value)">Click me</button>
</div>
`
})
export class TodoInput{
constructor(public todoService: TodoService){
}
onClick(todo: string){
this.todoService.todos.push(todo);
console.log(this.todoService.todos);
}
}
import {Component} from 'angular2/core';
import {TodoService} from './TodoService';
@Component({
selector: 'todo-list',
template: `
<ul>
<li *ngFor="#todo of todoService.todos">
{{todo}}
</li>
</ul>
`
})
export class TodoList{
constructor(public todoService: TodoService){
}
}
export class TodoService{
todos = [];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment