Retrieve date จาก Reactive Form ใน angular
Created At : 2023-09-18 23:35
Views 👀 :
ในการ retrieve date จาก Reactive Form ใน Angular เราสามารถใช้บริการ FormControl ของ Angular ได้
FormControl เป็นคลาสที่ช่วยให้เราสามารถจัดการข้อมูลในฟอร์มได้ โดยเราสามารถใช้ value property ของ FormControl เพื่อ retrieve ค่าของฟอร์มได้
ตัวอย่างการ retrieve date จาก Reactive Form
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import { Component , OnInit } from '@angular/core' ;import { FormBuilder , FormGroup } from '@angular/forms' ;@Component ({ selector : 'my-app' , templateUrl : './app.component.html' , styleUrls : ['./app.component.css' ] }) export class AppComponent implements OnInit { formBuilder : FormBuilder ; form : FormGroup ; constructor (private formBuilder: FormBuilder ) {} ngOnInit ( ) { this .form = this .formBuilder .group ({ date : new FormControl ('2023-08-22' , [Validators .required , Validators .date ]) }); } onSubmit ( ) { const date = this .form .get ('date' ).value ; console .log (date); } }
โค้ด HTML
1 2 3 4 <form [formGroup ]="form" (ngSubmit )="onSubmit()" > <input type ="date" formControlName ="date" > <button type ="submit" > Submit</button > </form >
Output
เมื่อเราป้อนวันที่ลงในฟอร์มและคลิกปุ่ม “Submit” โค้ดจะพิมพ์วันที่ลงในคอนโซล
วิธีอื่นในการ retrieve date จาก Reactive Form
นอกจากการใช้ value property แล้ว เรายังสามารถใช้ valueChanges observable ของ FormControl เพื่อ retrieve ค่าของฟอร์มได้
valueChanges observable จะส่งออกชุดของ values ใหม่ทุกครั้งที่ค่าของฟอร์มเปลี่ยนแปลง
ตัวอย่างการ retrieve date จาก Reactive Form โดยใช้ valueChanges observable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 import { Component , OnInit } from '@angular/core' ;import { FormBuilder , FormGroup } from '@angular/forms' ;@Component ({ selector : 'my-app' , templateUrl : './app.component.html' , styleUrls : ['./app.component.css' ] }) export class AppComponent implements OnInit { formBuilder : FormBuilder ; form : FormGroup ; constructor (private formBuilder: FormBuilder ) {} ngOnInit ( ) { this .form = this .formBuilder .group ({ date : new FormControl ('2023-08-22' , [Validators .required , Validators .date ]) }); this .form .get ('date' ).valueChanges .subscribe (date => { console .log (date); }); } }
โค้ด HTML
1 2 3 <form [formGroup ]="form" > <input type ="date" formControlName ="date" > </form >
Output
เมื่อเราป้อนวันที่ลงในฟอร์ม โค้ดจะพิมพ์วันที่ลงในคอนโซลทุกครั้งที่วันที่เปลี่ยนแปลง