AngularのForm(Template-driven Forms)メモ
(Angular v.4.3.6を利用)
<select>
を利用する
*ngFor
を利用する- AngularJSの
ng-options
のようなものはない
- AngularJSの
<select [(ngModel)]="model.power" name="power"> <option *ngFor="let pow of powers" [value]="pow">{{pow}}</option> </select>
NgFormとは
- https://angular.io/guide/forms#the-ngform-directive
Angular automatically creates and attaches an
NgForm
directive to the<form>
tag.
- https://angular.io/api/forms/NgForm
Creates a top-level FormGroup instance and binds it to a form to track aggregate form value and validation status.
<form #heroForm="ngForm">
ngModelとname属性
NgModel
インスタンスを取得
- template reference variableを利用する
<input type="text" [(ngModel)]="model.name" name="name" #name="ngModel">
参考
- https://angular.io/api/forms/NgModel
NgModel
はNgControl
をextendsしたもの- exportAsプロパティが'ngModel'
Directive({ selector: '[ngModel]:not([formControlName]):not([formControl])', providers: [formControlBinding], exportAs: 'ngModel' })
バリデーション
- https://angular.io/guide/form-validation#template-driven-validation
you add the same validation attributes as you would with native HTML form validation.
You can then inspect the control's state by exporting
ngModel
to a local template variable.
<input>
関連その他
参考
<input>
操作時のイベントを取得したい
<input (keyup)="onKey($event)">
$event
オブジェクトのプロパティはDOMイベントのタイプによって変わる
値の確認
onKey(event: KeyboardEvent) { console.log((<HTMLInputElement>event.target).value); }
$event
を利用せずに値を確認
(DOMイベント全体を渡さずに、値だけを渡したい。)
<!-- template reference variables を利用 --> <input #box (keyup)="onKey(box.value)">
キーイベントをフィルタリングしたい
<!-- Enterキーに反応 --> <input #box (keyup.enter)="onEnter(box.value)">