Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Sweet Angular, good forms never felt so good

Ciro Nunes
August 02, 2017

Sweet Angular, good forms never felt so good

Ciro Nunes

August 02, 2017
Tweet

More Decks by Ciro Nunes

Other Decks in Technology

Transcript

  1. import { NgModule } from '@angular/core'; import { BrowserModule }

    from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ BrowserModule, FormsModule ] }) export class AppModule {}
  2. import { NgModule } from '@angular/core'; import { BrowserModule }

    from '@angular/platform-browser'; import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ imports: [ BrowserModule, ReactiveFormsModule ] }) export class AppModule {}
  3. constructor(private fb: FormBuilder) { this.heroForm = fb.group({ name: ['', [Validators.required,

    Validators.minLength(3)]], rival: [], superpowers: fb.group({ invisibility: false, fly: false, nightVision: false, healing: false }, { validator: superpowersValidator }), sex: [], skills: fb.group({ programming: 0, bjj: 0, fifa: 0 }), github: [] }); }
  4. <div class="form-group form-group --big"> <input placeholder="Name *" formControlName="name"> <div *ngIf="heroForm.get('name').touched

    && heroForm.get('name').hasError('required')" > Name is <strong>required </strong> </div> <div *ngIf="heroForm.get('name').touched && heroForm.get('name').hasError('minlength')" > The min length for the name is <strong>3 </strong> </div> </div>
  5. constructor(private fb: FormBuilder) { this.heroForm = fb.group({ name: ['', [Validators.required,

    Validators.minLength(3)]], rival: [], superpowers: fb.group({ invisibility: false, fly: false, nightVision: false, healing: false }, { validator: superpowersValidator }), sex: [], skills: fb.group({ programming: 0, bjj: 0, fifa: 0 }), github: [] }); }
  6. export const superpowersValidator = (control: AbstractControl) => { const invisibility

    = control.get('invisibility'); const fly = control.get('fly'); const healing = control.get('healing'); const nightVision = control.get('nightVision'); const fields = [invisibility, fly, healing, nightVision] .filter(field => field.value === true); if (fields.length < 2) { return { atleasttwo: true }; } return null; };
  7. T akeaways Both styles can be used in the same

    app Pick up the one that works the best for each situation
  8. T akeaways Both styles can be used in the same

    app Pick up the one that works the best for each situation Embrace Observables