custom validatior unable to get disable field value anguar template driven field

Discussão em 'Angular' iniciado por Angular Guru, Outubro 26, 2024.

  1. Angular Guru

    Angular Guru Guest

    I am using angular template driven form.I created custom validation function in directive also I add validation throw directive . but disable fields I am unable to get value. if disable fields having value but validators throw error. if disable fields empty is I need error. I tried many control.value, control.getRawValue, control.get('value')

    <form #f="ngForm">
    <select name="options" [(ngModel)]="data.option">
    <option value="1"> option1</options>
    <option value="2"> option2</options>
    <option value="3"> option3</options>
    </select>

    <input type="text" [(ngModel)]="data.text1" [disable]="data.option !==1" appdirective1>
    <input type="text" [(ngModel)]="data.text2" [disable]="data.option !==2" appdirective1>
    <input type="text" [(ngModel)]="data.text3" [disable]="data.option !==3">

    </form>

    {{f.valid |json }}



    @Directive({
    selector: '[appdirective1]',
    })
    export class directiveName implements OnChanges, OnInit {

    constructor(private _injector: Injector,private el:ElementRef, , render:Renderer2) {}

    validate1(): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {

    const c=control.value;
    const status=(c === undefined || c===null || c==='')? true:false
    //writing some logic here then assign value status;
    if(status){
    this.render.addClass(this.e1.nativeElement, 'is-invalid');
    return{invalid:true}
    }else{
    this.render.removeClass(this.e1.nativeElement, 'is-invalid');
    return null;
    }

    };
    }

    ngOnInit() {
    this.conditionallyAddValidators();
    }

    conditionallyAddValidators() {
    const control = this._injector.get(NgControl);
    control?.control?.addValidators(this.validate1());

    control?.control?.updateValueAndValidity();
    }

    ngOnChanges() {
    this.conditionallyAddValidators();
    }
    }


    Example URL : https://stackblitz.com/edit/stackblitz-starters-ud5jux?file=src/main.ts

    Continue reading...

Compartilhe esta Página