Lab 14 - Reactive Forms
Intro
In this lab we will create a form to allow a building name to be edited
1. Create a new component and add it to the menu / navigation
-
Create a component to edit a building
-
Add a route to display the edit building component, and a menu link.
2. Get the list of buildings
- In the new edit-building component, get a list of buildings and populate these as an unordered list. Each entry should have an edit button.
Click here to see the sample solution
import { Component, OnInit, signal, inject } from '@angular/core';
import { RestService } from '../rest.service';
import { Building } from '../data/Building';
@Component({
selector: 'app-edit-building',
standalone: true,
imports: [],
templateUrl: './edit-building.component.html',
styleUrl: './edit-building.component.css'
})
export class EditBuildingComponent implements OnInit {
buildings = signal<Building[]>([]);
private restService = inject(RestService);
ngOnInit(): void {
this.restService.getBuildings().subscribe(data => {
this.buildings.set(data);
});
}
}
<h2>Select the building to edit</h2>
<ul>
@for(building of buildings(); track $index) {
<li>
{{ building.name }} <button>edit</button>
</li>
}
</ul>
- Create a function to handle the click buttons and bind these to the button click events. The function should store the selected user's id in a class level
Click here to see the sample solution
selectedBuildingId : number | null = null;
handleClick(id :number) {
console.log("edit building with id: " + id);
this.selectedBuildingId = id;
}
<button (click)="handleClick(building.id)" >edit</button>
- Create an edit form on the HTML - only show this if there is a selected building.
@if(selectedBuildingId) {
<form >
<input type="hidden" id="id" name="id"/>
<label>
Name:
<input id="name" name="name"/>
</label>
<button>Save Changes</button>
</form>
}
- Create a FormGroup to represent the building. Ensure you import the ReactiveFormsModule into the component
Click here to see the sample solution
editForm = new FormGroup({
id: new FormControl('id'),
name: new FormControl('name'),
})
- Populate the form with data - when the user clicks to edit a building, use the ID to retrieve the building name and patch these into the form group.
Click here to see the sample solution
handleClick(id :number) {
this.selectedBuildingId = id;
this.editForm.patchValue({
id: "" + id,
name: this.buildings().find(b => b.id === id)?.name
})
}
- Create a function to bind to the submit event of the form, and make the binding. For now, just log out the new data
Click here to see the sample solution
onSubmit() {
console.log("Submitting form", this.editForm.value);
}
<form [formGroup]="editForm" (submit)="onSubmit()">
- Test this in your browser.