Forms

So far we've only looked at static website design and reading data. Forms allow users to input data. There are two different ways to do forms in Angular Template-driven and Reactive.

Also here's a cheatsheet on types of databinding in Angular, which i will go into more detail on later:

Template-Driven Forms

Template Form Validation

// When the input box is invalid 
// and has been touched change border to red
input.ng-invalid.ng-touched {
  border: 1px solid #f00;
} 
<form #userForm="ngForm">
...
<button type="submit" class="btn btn-primary" (click)="onSubmit()" [disabled]="userForm.invalid">Save</button>

Reactive Forms

  roomForm = new FormGroup({
    roomName : new FormControl('roomName')
  });
<form [formGroup]="roomForm"> 
  <div class="form-group">
    <label for="name">Name</label>
        <!-- Notice below the formControlName doesn't need to be bound with [] bc the formGroup has already been applied -->
    <input type="text" class="form-control" id="name" placeholder="room name" [formControlName]="roomName">
    <div class="alert alert-danger"></div>
  </div>
  <button type="button" class="btn btn-primary" (click)="onSubmit()">Save</button>
</form>
  ngOnInit(): void {
    this.roomForm.patchValue({
      roomName : this.room.name,
      location : this.room.location
    });
  }
  
  onSubmit(): void {
    this.room.name = this.roomForm.controls['roomName'].value;
    this.room.location = this.roomForm.value['location'];
    // TODO: Call a method in the dataService to save the room
  }
  constructor(private formBuilder: FormBuilder) {
 }

 ngOnInit(): void {
   this.roomForm = this.formBuilder.group({
     roomName : this.room.name,
     location : this.room.location
   });

   for (const layout of this.layouts) {
     const layoutCapacity = this.room.capacities.find( (lc) => lc.layout === Layout[layout]);
     const initialCapacity = layoutCapacity == null ? 0: layoutCapacity.capacity;
     this.roomForm.addControl(`layout${layout}`, this.formBuilder.control(initialCapacity));
   }
 }
  <div class="form-group" *ngFor="let layout of layouts">
   <label for="layout{{layout}}">{{ layoutEnum[layout] }}</label>
     <input type="number" class="form-control" id="layout{{layout}}" formControlName="layout{{layout}}">
 </div>
    this.roomForm = this.formBuilder.group({
     roomName : [this.room.name , Validators.required],
     location : [this.room.location, [Validators.required, Validators.minLength(2)]]
   });

Revision #2
Created 16 April 2022 23:24:24 by Elkip
Updated 16 April 2022 23:40:55 by Elkip