'Angular2: Template-Driven Validation of an input field with multiple validation functions
I have a component, where I have created a form composed of a select HTML attribute and an input field. The idea is that the input field must be validated based on the user choice from the select attribute.
HTML code:
<select class="form-control"
(ngModelChange)="onSelectedType($event)"
[(ngModel)]="av.type"
>
<option value="dateValue" [ngValue]="'dateValue'">Date</option>
<option value="numberValue" [ngValue]="'numberValue'">Number</option>
</select>
<input type="text"
name="value"
class="form-control"
placeholder="Value"
required
ngModel
(ngModelChange)="validateInput($event)"
#value="ngModel"
[appAvValue]="av.type">
In my component I have a function (onSelectedType) which is able to catch the choice and set it to an object, from which the input is reading (av.type). I have created also a directive where based on the input type (av.type) I try to set different validator functions.
TS code:
@Directive({
selector: '[appAvValue]',
providers: [{
provide: NG_VALIDATORS,
useExisting: AvValueDirective,
multi: true
}]
})
export class AvValueDirective implements Validator {
@Input() appAvValue: string; /* The directive type */
constructor() { }
validate(control: AbstractControl): ValidationErrors | null {
switch (this.appAvValue) {
case 'numberValue':
return createNumberValidator()(control);
case 'dateValue':
return createDateValidator()(control);
}
return undefined; /* As default case for the stringValue */
}
}
The problem is that the Directive doesn't call the validate method although the value (av.type) changes. What is the reason behind it? (I checked this post also, but there the difference is that function gets passed through the input.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
