Skip to content

Instantly share code, notes, and snippets.

@nicobytes
Last active November 8, 2023 05:45
Show Gist options
  • Save nicobytes/4b583a0f5a769c566ba7659170d48f6b to your computer and use it in GitHub Desktop.
Save nicobytes/4b583a0f5a769c566ba7659170d48f6b to your computer and use it in GitHub Desktop.
FormControl with Angular

1. Init

ng new angular-forms

2. Create component

ng g c components/product-form

3. Include reactive forms

import { ReactiveFormsModule } from '@angular/forms';

ng g c components/product-form

4. FormControl

emailCtrl = new FormControl('', []);
<p>
  Email: <br/>
  <input type="email" [formControl]="emailCtrl">
</p>

5. Get value

getEmail(event: Event) {
  event.preventDefault();
  console.log(this.emailCtrl.value);
}
<p>
  Email: <br/>
  <input type="email" fromControlName="email">
</p>
<button type="button" (click)="getEmail($event)">Save</button>
this.emailCtrl.valueChanges
.subscribe(value => {
  console.log(value);
});

6. Debounce

this.emailCtrl.valueChanges
.pipe(
  debounceTime(500)
)
.subscribe(value => {
  console.log(value);
});

7. Validations

emailCtrl = new FormControl('', [Validators.required]);

8. Show validations

<p>
  Email: <br/>
  <input type="email" [formControl]="emailCtrl">
</p>
<p>
  <small *ngIf="emailCtrl.hasError('required') && emailCtrl.dirty">El campo es requerido</small>
</p>
<button [disabled]="emailCtrl.invalid" type="button" (click)="getEmail($event)">Save</button>

9. Group validations

emailCtrl = new FormControl('', [Validators.required]);
<p>
  Email: <br/>
  <input type="email" [formControl]="emailCtrl"> <br/>
</p>
<div>
  <p *ngIf="emailCtrl.errors && emailCtrl.dirty">
    <small *ngIf="emailCtrl.hasError('required')">El campo es requerido</small>
    <small *ngIf="emailCtrl.hasError('minlength')">Debe ser mínimo de 4</small>
  </p>
</div>
<button [disabled]="emailCtrl.invalid" type="button" (click)="getEmail($event)">Save</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment