[Angular 2] Adding a data model

时间:2022-04-14 07:10:30

Instead of add todo as a string, we create a data model:

export class TodoModel{
    constructor(
        public title: string = ""
    ){}
}


export class TodoService{
    todos: TodoModel[] = [
        new TodoModel('eat'),
        new TodoModel('sleep'),
        new TodoModel('work')
    ];

    addTodo(value: TodoModel):void {
        this.todos.push(value);
    }
}

 

todoInput.ts

import {Component, View, FORM_DIRECTIVES} from "angular2/angular2";
import {TodoService, TodoModel} from "./todoService";
@Component({
    selector: 'todo-input'
})
@View({
    directives: [FORM_DIRECTIVES],
    template: `
        <form action="" (ng-submit)="onSubmit()">
            <input type="text" [(ng-model)]="todoModule.title">
        </form>
    `
})
export class TodoInput{
    todoModule:TodoModel = new TodoModel();

    constructor(
        //@Inject(TodoService) todoService
        public todoService:TodoService
    ){
        this.todoService = todoService;
    }

    onSubmit(){
        this.todoService.addTodo(this.todoModule);
        this.todoModule = new TodoModel(); // reinit the this.todoModule
    }
}