Angular Reactive Forms – 3

Melanjutkan dari modul sebelumnya, sekarang kita akan membahas submit form.

Buka file app.component.html, tambahkan event binding untuk ngSubmit directive.

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">

Perbedaan dengan pendekatan template driven, kita tidak perlu menggunakan local reference.

Kemudian buka file app.component.ts, tambahkan method onSubmit() untuk handling submit form.

onSubmit(){
  console.log(this.myForm);
}

Berikut isi lengkap file app.component.html

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
      <form [formGroup]="myForm" (ngSubmit)="onSubmit()">
        <div class="form-group">
          <label for="username">Username</label>
          <input
            type="text"
            id="username"
            class="form-control"
            formControlName="username">
        </div>
        <div class="form-group">
          <label for="email">email</label>
          <input
            type="text"
            id="email"
            class="form-control"
            formControlName="email">
        </div>
        <div class="radio" *ngFor="let gender of genders">
          <label>
            <input
              type="radio"
              [value]="gender"
              formControlName="gender">{{ gender }}
          </label>
        </div>
        <button class="btn btn-primary" type="submit">Submit</button>
      </form>
    </div>
  </div>
</div>

file app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  genders = ['male', 'female'];
  myForm! : FormGroup;

  ngOnInit(){
    this.myForm = new FormGroup({
      'username' : new FormControl(null),
      'email' : new FormControl(null),
      'gender' : new FormControl('male')
    });
  }

  onSubmit(){
    console.log(this.myForm);
  }
}

Sesuai ekspektasi, form template sudah terhubung dengan form control pada typescript dan kita sudah bisa menerima data yang di submit form.

Sharing is caring:

Leave a Comment