Sudut 2
Bagi siapa pun yang ingin melakukan hal yang sama di Angular 2 itu sangat mirip selain mendapatkan formulirnya
<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
}
}
}