angularメモ帳

angular始めました。
動かすために調べたことをメモしています。

512 views

フォームを作成する

ブラウザでよく使用するフォームを作成してみます。

本章で作成するフォームは次のとおりです。
* htmlには名前と年齢を入力するテキストエリアと、OKボタンのフォームを表示する
* OKボタンを押すとコンポーネントがフォームの値を受け取りコンソールに入力された名前と年齢を出力する

モジュールの設定

フォームを利用するにはFormのモジュールをインポートする必要があります。
app.module.tsに以下の★のコードを追加します。

[app.module.ts]

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';//★

import { AppComponent } from './app.component';
import { HelloComponent } from './hello/hello.component';

const routes:Routes = [
  {path:'hello', component:HelloComponent}
];

@NgModule({
  declarations: [
    AppComponent,
    HelloComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,//★
    RouterModule.forRoot(routes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

次にhello.component.tsにフォームグループを作成します。

hello.compoent.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';//★

@Component({
  selector: 'app-hello',
  templateUrl: './hello.component.html',
  styleUrls: ['./hello.component.css']
})
export class HelloComponent implements OnInit {
  sampleFormGroup = new FormGroup({//★
    name: new FormControl(''),//★
    age: new FormControl(0)//★
  });//★

  constructor() { }

  ngOnInit(): void {

  }

  onClick() {//★
    let result = this.sampleFormGroup.value;//★
    console.log(result.name);//★
    console.log(result.age);//★
  }//★
}

2行目で、FomrControlとFormGroupのモジュールをインポートしています。
10行目~13行目でFormGroupを作成しています。
11行目と12行目はそれぞれ名前を入力するためのFormControlと年齢を入力するコントロールです。
それらをまとめているのがFormGroupになります。

21行目~25行目はonClick関数で、ボタンをクリックされたときに呼び出されます。
呼び出されたら、フォームの値をコンソールに出力しています。

最後にhello.compoent.htmlです。

[hello.compoent.html]

<p>hello works!</p>
<form [formGroup]="sampleFormGroup" (submit)="onClick()">
    <input type="text" formControlName="name" />
    <input type="number" formControlName="age" />
    <input type="submit" value="click" />
</form>

2行目で、hello.compent.10行目で宣言しているsampleFormGroupをformに設定し、submitした場合にonClickが呼ばれるように定義しています。
name,ageの入力はFormGroup内のコントローラーと紐づきます。
以下のように名前と年齢を入力し、clickボタンを押すと、コンソールに名前と年齢が表示されます。

Page 8 of 38.

前のページ 次のページ



[添付ファイル]

1.angular flex layoutについて.docx  


お問い合わせ

プロフィール

すぺぺぺ

自己紹介

本サイトの作成者。
プログラムは趣味と勉強を兼ねて、のんびり本サイトを作っています。
フレームワークはdjango。
ChatGPTで自動プログラム作成に取り組み中。

サイト/ブログ

https://www.osumoi-stdio.com/novel/

ツイッター

@darkimpact0626