Skip to content

Instantly share code, notes, and snippets.

@zhentian-wan
Created March 21, 2016 08:30
Show Gist options
  • Save zhentian-wan/6569be1bff44bb5a9a0b to your computer and use it in GitHub Desktop.
Save zhentian-wan/6569be1bff44bb5a9a0b to your computer and use it in GitHub Desktop.
Angular 2 property syntax
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';
import {TodoModule} from './TodoModule';
@Component({
selector: 'todo-input',
template: `
<form (submit)="onSubmit()">
<input type="text" [(ngModel)]="todoModule.title">
</form>
`
})
export class TodoInput {
// Init a todoModule
todoModule:TodoModule = new TodoModule();
constructor(public todoService:TodoService) {
}
onSubmit() {
this.todoService.todos.push(this.todoModule);
// After insert, create new TodoModule
this.todoModule = new TodoModule();
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">
<span [hidden]="todo.status == 'completed'"
[contentEditable]="todo.isEdit">{{todo.title}}</span>
<button (click)="todo.toggle()">Toggle</button>
<button (click)="todo.edit()">Edit</button>
</li>
</ul>
`
})
export class TodoList{
constructor(public todoService: TodoService){
}
}
export class TodoModule{
status: string = "started";
isEdit: boolean = false;
constructor(public title:string=""){
}
toggle(){
this.status = this.status === "started" ?
"completed":
"started";
}
edit(){
this.isEdit = !this.isEdit;
}
}
import {TodoModule} from './TodoModule';
export class TodoService{
todos = [
//init some todos
new TodoModule("eat"),
new TodoModule("sleep"),
new TodoModule("code")
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment