angularメモ帳

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

575 views

バリデーション エラーメッセージ表示

hello.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } 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('', [Validators.required]),
    age: new FormControl(0, [Validators.required, Validators.min(18), Validators.max(65)])
  });

  constructor() { }

  ngOnInit(): void {

  }

  get name() {
    return this.sampleFormGroup.get('name');
  }

  get age() {
    return this.sampleFormGroup.get('age');
  }

  onClick() {
    //コンポーネントでバリデーションを行う場合。
    if(this.sampleFormGroup.invalid) {

      if(this.sampleFormGroup.get("name").errors?.required) {
        console.log("名前が入力されていない");
      }

      if(this.sampleFormGroup.get("age").errors?.required) {
        console.log("年齢が入力されていない");
      }

      if(this.sampleFormGroup.get("age").errors?.min) {
        console.log("18未満の数字が指定されている");
      }

      if(this.sampleFormGroup.get("age").errors?.max) {
        console.log("65より大きいの数字が指定されている");
      }
    }
    else {
      console.log("正常な入力です");
    }
  }
}

hello.component.html

<p>hello works!</p>
<form [formGroup]="sampleFormGroup" (submit)="onClick()">
    <span>
        <div *ngIf="name.errors != null && name.errors.required">名前を入力してください</div>
        <input type="text" formControlName="name" />
    </span>

    <span>
        <div *ngIf="age.errors != null && age.errors.required">年齢を入力してください</div>
        <div *ngIf="age.errors != null && age.errors.min">18以上を入力してください</div>
        <div *ngIf="age.errors != null && age.errors.max">65以下の値を入力してください</div>
        <input type="number" formControlName="age" />
    </span>
    <input type="submit" value="click" />
</form>

Page 12 of 38.

前のページ 次のページ



[添付ファイル]

1.angular flex layoutについて.docx  


お問い合わせ

プロフィール

すぺぺぺ

自己紹介

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

サイト/ブログ

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

ツイッター

@darkimpact0626