import {Component} from 'angular2/core'; import {StudentFormComponent } from './student-form' @Component({ selector: 'appTest',template: '<student-form></student-form>',directives: [StudentFormComponent ] }) export class App { }
/** * Created by dell on 2016/9/8. */ import {Component} from 'angular2/core'; import {NgForm} from 'angular2/common'; import { Student} from './student'; @Component({ selector: 'student-form',templateUrl: 'app/student-form.html' }) export class StudentFormComponent { studentList:Student[] = []; student= new Student('马云',25,"北京市花神街39号"); get studentInfo() { return JSON.stringify(this.student); } onSubmit(value: Student): void { console.log('you submitted value: ',JSON.stringify(value)); this.studentList.push(value); } }
<h1>This is A Student Data!</h1> <p>StudentInfo: {{studentInfo}}</p> <div *ngFor="#stu of studentList"> <span>{{stu.name}}</span> </div> <h1>Student Form</h1> <form (ngSubmit)="onSubmit(studentForm.value)" #studentForm="ngForm"> <div > <label>名字</label> <input type="text" required [(ngModel)]="student.name" ngControl="name"> </div> <div> <label>年龄</label> <input type="text" required [(ngModel)]="student.age" ngControl="age"> </div> <div> <label>住址</label> <input type="text" [(ngModel)]="student.address" ngControl="address"> </div> <button type="submit">Submit</button> </form>
/** * Created by dell on 2016/9/8. */ export class Student{ constructor( public name: string,public age: number,public address?: string ) { } }原文链接:https://www.f2er.com/angularjs/148893.html