Reactive Formsでフォーム作成方法 – Angular
| 項目 | バージョン |
|---|---|
| Angular | 16.0.2 |
| node | 18.16.0 |
| npm | 9.5.1 |
プロジェクト作成
プロジェクト作成します。
$ ng n reactive-test --standalone
app.component.html
入力部品にformControlNameを指定します。
以下チュートリアルでは(submit)を使用していますが、(ngSubmit)を使用したほうが良いです。
https://angular.jp/tutorial/first-app/first-app-lesson-12 ← (submit)
https://angular.jp/guide/reactive-forms ← (ngSubmit)
<form [formGroup]="formData" (ngSubmit)="submitNow()"> <label for="first-name">First Name</label> <input id="first-name" type="text" formControlName="firstName"> <br> <label for="last-name">Last Name</label> <input id="last-name" type="text" formControlName="lastName"> <br> <label for="email">Email</label> <input id="email" type="email" formControlName="email"> <br> <button type="submit">submit now!</button> </form>
app.component.ts
以下importします。
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
ReactiveFormsModuleをimportsに追加します。
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, ReactiveFormsModule],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
app.component.ts
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, ReactiveFormsModule],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'reactive-test';
formData = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
email: new FormControl('')
});
submitNow() {
alert(JSON.stringify(this.formData.value));
}
}
ローカルサーバ起動
起動します。
$ ng s --open
リアクティブフォームの動作確認ができます。
参考サイト
https://www.learmoreseekmore.com/2022/06/angular14-reactive-forms-example.html
https://www.web-dev-qa-db-ja.com/ja/angular/angular-submitイベントとngsubmitイベントの違いは?/828715142/
Template-driven Forms in Angular
In this article we discuss the template-driven forms in Angular and all the directives that come into play.

KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES20xx),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^



コメント