4.2 Angular Form template driven form - quan1997ap/angular-app-note GitHub Wiki

1. Form Group

Chú ý: Dùng min max chỉ dành cho input type = text. Giải quyết bằng custom directive

image image

<form #form="ngForm" name="test">
  <label for="length">Test</label>
  <input
    name="age"
    type="text"
    [(ngModel)]="data.age"
    min="5"
    max="10"
  />
</form>

2. Form Array

=> Template-driven form không có form array. Ý tưởng là tạo nhiều form group với groupName = index => Tận dụng được phần validate của Template-driven form

Form Group {
   1: { Form Group }
   2: { Form Group }
}
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { LAYOUT_CONFIG } from 'src/app/core/configs/cbbank-layout.config';
// https://ramya-bala221190.medium.com/implementing-dynamic-template-driven-forms-in-angular-40527de8c064

@Component({
  selector: 'app-customer-management',
  templateUrl: './customer-management.component.html',
  styleUrls: ['./customer-management.component.scss']
})
export class CustomerManagementComponent implements OnInit {

  LAYOUT_CONFIG = LAYOUT_CONFIG;

  constructor() { }
  mydata: any[]= [];
  prio = [0, 1, 2];
  SampleForm: any;
  title: string ="";
  completed: boolean = false;
  priority: number = 0;
  ngOnInit(): void {
    this.mydata = [
    {
      id: 1,
      title: "1",
      priority: 1
    },
    {
      id: 2,
      title: "2",
      priority: 2
    },
    {
      id: 1,
      title: "3",
      priority: 3
    },
  ];
  }

  track(item: any, index: number) {
    return index;
  }

  sub(formGroup: any){
    console.log(formGroup)
  }

  getTitleControl(formGroup:any){
    return formGroup.controls.title;
  }
  
  show(formGroup: any){
    console.log(formGroup.controls.title)
  }
}

<form class="form-group" #formDemo="ngForm" (ngSubmit)="sub(formDemo)">
  <table class="table-bordered">
    <tr>
      <th>Item Name</th>
      <th>Completed</th>
      <th>Priority</th>
      <th>Action</th>
    </tr>
    <tr *ngFor="let x of mydata;let ind=index;trackBy:track" ngModelGroup="{{ind}}">
      <td>
        <input class="form-control" required type="text" ngModel [(ngModel)]="x.title" name="title" placeholder="Item name">
        <button (click)="show(formDemo.controls[ind])">
          click
        </button>
        <div class="col alert alert-danger" role="alert"
              *ngIf="getTitleControl(formDemo.controls[ind]).errors?.required">
              Name is required!
        </div>

      </td>
      <td><select class="form-control" [(ngModel)]="x.priority" name="priority">
          <option *ngFor="let y of prio">{{y}}</option>
        </select>
      </td>
    </tr>
  </table>
</form>

⚠️ **GitHub.com Fallback** ⚠️