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?
You should use ReactiveFormsModule. It has change detection and validation handling.
I gave an answer that involved cookies an a template for Required validation here.
Download the example, have a play around with the live example.
If you hover over links you'll see one has 'final' in link. The other you'd have to go thru and add code manually. I'd suggest using 'final' version.
Also if you go to Angular.io and search on "validator" you'll be able to find examples of things like EmailValidator, PatternValidator. Here's the main Validators class.
If you want to learn more Angular University has an excellent course on it.
They've got a YouTube channel and their code is on Github.
You need to work out which branches to check out from following along with videos:
"Rxjs and Reactive Patterns Angular Architecture Course".