角 2
对于任何希望在 Angular 2 中做同样事情的人来说,除了掌握表格之外,它非常相似
<form role="form" [ngFormModel]="myFormModel" (ngSubmit)="onSubmit()" #myForm="ngForm">
<div class="form-group">
<label for="name">Name</label>
<input autofocus type="text" ngControl="usename" #name="ngForm" class="form-control" id="name" placeholder="Name">
<div [hidden]="name.valid || name.pristine" class="alert alert-danger">
Name is required
</div>
</div>
</form>
<button type="submit" class="btn btn-primary" (click)="myForm.ngSubmit.emit()">Add</button>
import { Component, } from '@angular/core';
import { FormBuilder, Validators } from '@angular/common';
@Component({
selector: 'my-example-form',
templateUrl: 'app/my-example-form.component.html',
directives: []
})
export class MyFormComponent {
myFormModel: any;
constructor(private _formBuilder: FormBuilder) {
this.myFormModel = this._formBuilder.group({
'username': ['', Validators.required],
'password': ['', Validators.required]
});
}
onSubmit() {
this.myFormModel.markAsDirty();
for (let control in this.myFormModel.controls) {
this.myFormModel.controls[control].markAsDirty();
};
if (this.myFormModel.dirty && this.myFormModel.valid) {
// My submit logic
}
}
}