Adding Specialty Pizzas using patchValue
Explore how to use patchValue in Angular reactive forms to add specialty pizzas like Hawaiian and Buffalo Chicken. Understand how to manage partial data models and enable user customization within reactive forms, improving dynamic form handling and user interaction in your application.
We'll cover the following...
In our case, the specials will be pre-configured collections of toppings (nothing too crazy). This also lets the user customize the specials (maybe you’re not a fan of hot sauce but love everything else about buffalo chicken).
patchValue in reactive form
The traditional form story doesn’t provide much comfort here, but through patchValue, reactive forms make this easy.
First, let’s set up two specials for today:Hawaiian and Buffalo Chicken.
We’ll add the following code as a property declaration on the component class:
Both of these are partial models because, they define only part of a pizza model. A special shouldn’t define the size of a pizza, so we’ll leave that up to whatever the user chooses. Just iterate over the specials and display a button for each.
We’ll add the following where the <!-- TODO: specials -->
comment is in pizza-order.component.html:
<h3>Make it a Special</h3>
<button *ngFor="let s of specials" (click)="selectSpecial(i, s)">
{{ s.name }}
</button>
The selectSpecial method is simple to implement because it’s just a wrapper around patchValue:
Pizza ordering form with specialty pizzas
import { AppPage } from './app.po';
describe('pizza App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('Welcome to app!');
});
});
Achievement Unlocked! 🎉
Congratulations! You have built a complete application for a pizza shop!
Brilliant work! Give yourself a round of applause!