mercredi 19 juillet 2017

Angular 4: Best practices to catch custom error from model

I have an Angular4 application which the model does all the validation stuff while inputing the data (if the input is wrong the model throws an error and do not set the variable), so the ideal case would be to link any input change directly to the set method related to the model, these would make the components very lean and scaleable. My first strategy was to make a directive which I pass the setter method and my directive does the try/catch handle

My html would be:

<div class="input-field col s12" appFormSetter [setFunction]="session?.getPlayer()?.setName">
   <i class="material-icons prefix">account_circle</i>
   <input #input placeholder="João da Silva" type="text" class="validate" 
          [ngModel]='session.getPlayer()?.getName()' name="name">
   <label for="first_name" class="active">Nome</label>
</div>

The directive would be:

import { Directive, HostListener, Input, ElementRef } from '@angular/core';
@Directive({
   selector: '[appFormSetter]'
})
export class FormSetterDirective {

  @Input() setFunction;

  @HostListener('input') onInput() {
    try {
        this.setFunction(this.elRef.nativeElement.value);
    } catch (error) {
        // Would catch the error and show in some <small>
        console.log('Error', error);
    }
  }

  constructor(private elRef: ElementRef) {
    console.log('mychildren', this.inputElement);
  }
}

And the model would be:

public setName(name: string): void {
    if(!isValid()) throw 'myError';
    this.name = name;
}

What is the best practices to handle something like this? Can I get the error directly through the html without going through the directive?

Aucun commentaire:

Enregistrer un commentaire