I just red angular 2 cookbook in how you I can create dynamic forms but I wander how I can add custom validators to particular field.
questions.forEach(question => {
group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)
: new FormControl(question.value || '');
});
Here they form a from group to hold form inputs so what about if I want to apply a particular validation to a particular question Ex: if I has input for confirming password matching. I know that there is validateequal
attribute to do this task how I can apply this validateequal
or even create my own custom validation
Note that it is dynamic form which means could hold any input for example i am planning to use the same form to generate log in form which means that it only has password input , i need away to check if there is input will hold password and if any will hold password confirmation and if so then i need to check if they are matching before submit
alrighty, I think I have it.
You're going to use custom directives in order to get the Job done.
Here is a very rudimentary tutorial on custom directives https://angular.io/docs/ts/latest/guide/attribute-directives.html
if you create that however you're templating your app, you can easily modify it to fit your parameters.
in mine, i've used that example in the following way.
Your NgModule || app.module.ts
import { customDirective } from '../directive/path';
Your customDirective.ts || js
import {Directive, HostListener, Input, ElementRef} from '@angular/core';
@Directive({
selector: '[fooSelector]'
})
export class CustomDirective {
constructor(private el: ElementRef, private renderer: Renderer) {}
@Input('fooSelector') testing: Object;
//this controls event type with change being the event
@HostListener('change') onChange(){
this.logicFunct(this.htmlAttr); //will define htmlAttr in template
}
//this is the validator logic
private logicFunct($obj: Object){
// submit logic here - for ex:
if($obj != 'test) {
this.varBar = true; //check template ngIf
}
}
}
Your Template
<input
type="text"
#htmlAttr
[fooSelector]="this.htmlAttr._value"
*ngIf="!this.varBar">
</input>
I'm almost positive there are other better ways to do this, and if someone has one, please let us know!
Hope this helps anyone stumbling upon it.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments