Skip to content

Commit 70bbf3c

Browse files
geromegrignond3lm
authored andcommitted
feat: add form item
1 parent fd72b39 commit 70bbf3c

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

content/forms/.category

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
---
2+
title: Forms
3+
summary: This category summarizes best practices regarding Forms.
4+
---
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
---
2+
title: Do not mix Angular Forms API
3+
---
4+
5+
# Problem
6+
7+
Angular provides two APIs for building forms: the `Template-driven` and the `Reactive` forms API.
8+
Both APIs can be used to build forms in Angular, but they are not meant to be mixed.
9+
Mixing these APIs can lead to confusion and make the code harder to maintain.
10+
11+
Here is an example of mixing the two APIs:
12+
13+
```ts
14+
import { FormControl } from '@angular/forms';
15+
16+
@Component({
17+
template: `
18+
<form [formGroup]="form">
19+
<input formControlName="name" [(ngModel)]="name" name="name" required>
20+
<button type="submit">Submit</button>
21+
</form>
22+
`
23+
})
24+
export class SomeComponent {
25+
name: string = 'Gerome';
26+
27+
form = new FormGroup({
28+
name: new FormControl('Gerome', {Validators.required})
29+
});
30+
}
31+
```
32+
33+
In this example, we are using both `formControl` and `ngModel` to bind the input field to the `name` property.
34+
35+
# Solution
36+
37+
Choose one API and stick to it. If you are using the `Reactive` forms API, then use it consistently throughout your application.
38+
39+
Here is the same example using the `Reactive` forms API:
40+
41+
```ts
42+
import { FormControl } from '@angular/forms';
43+
44+
@Component({
45+
template: `
46+
<form [formGroup]="form">
47+
<input formControlName="name">
48+
<button type="submit">Submit</button>
49+
</form>
50+
`
51+
})
52+
export class SomeComponent {
53+
form = new FormGroup({
54+
name: new FormControl('Gerome', {Validators.required})
55+
});
56+
}
57+
```

0 commit comments

Comments
 (0)