0

Создал пользовательский контрол для формы.

CustomControlComponent.html

<div fxLayout='row' fxLayoutAlign="end center" class="app-password">
  <input fxFlex kendoTextBox 
    [ngClass]="{ 'ng-dirty': isDirty }"
    [(value)]="currentValue"  
    [attr.type]="type"
    [disabled]="isDisabled"
    (touched) ="onTouched($event)"
    (input)="onChange($event)"
    (blur)="onBlur()"
    (focus)="onFocus()"
  /><span   [ngClass]="{'k-icon': true, 'k-i-unlock': isShowPassword , 'k-i-lock': !isShowPassword }" 
    (mouseup)="onMouseUp()"
    (mousedown)="onMouseDown()"
    ></span>
</div>

CustomControlComponent.ts

import { Component, forwardRef, OnInit, Input } from '@angular/core';
import { ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-custom-control',
  templateUrl: './CustomControl.component.html',
  styleUrls: ['./CustomControl.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => PasswordComponent),
      useValue: (c: FormControl) => PasswordComponent,
      multi: true
    }
  ]
})
export class CustomControl implements ControlValueAccessor, OnInit {
  public isDisabled: boolean;
  public isDirty = false;
  public type = 'password';
  public isShowPassword = false;
  public currentValue: string = null;
  // Events change and touched
  private propagateChange = (_: any) => { };
  private propagateTouched = () => { };

  constructor() { }

  public ngOnInit() { }

  public writeValue(password: string): void {
    if (!password || typeof password !== 'string') {
      return;
    }
    this.currentValue = password;
    this.propagateTouched();
    this.propagateChange(this.currentValue);
  }

  public registerOnChange(fn: any): void {
    console.log(fn);
    this.propagateChange = fn;
  }

  public registerOnTouched(fn: any): void {
    this.propagateTouched = fn;
  }

  public setDisabledState?(isDisabled: boolean): void {
    this.isDisabled = isDisabled;
  }

  public get value(): string {
    return this.currentValue;
  }

  public onTouched(event) {
    this.propagateTouched();
  }

  public onShow() {
    if (this.type === 'password') {
      this.type = 'text';
    } else {
      this.type = 'password';
    }
  }

  public onMouseUp() {
    this.type = 'password';
    this.isShowPassword = false;
  }

  public onMouseDown() {
    this.type = 'text';
    this.isShowPassword = true;
  }

  public onChange(event) {
    this.writeValue(event.target.value);
  }


  public onBlur() {

  }

  public onFocus() {
    this.isDirty = true;
    this.propagateTouched();
  }

}

Создал котнрол

import { FormControl, FormGroup, Validators } from '@angular/forms';
.....
    const passwordControl = new FormControl(null, [Validators.requirement, Validators.max(3)]) 

Использую в Reactive Forms

<app-custom-control [formControlName]="'password'" ></app-custom-control>

Вопрос как в созданом пользовательском контроле узнать что данное поле не прошло валидацию ?

1 ответ 1

0

Вы можете поступить следующим образом - повесить обработчик события на инпут, как пример:

<input fxFlex (keyup)="validate($event.target.value)">

В компоненте CustomControl создать генератор событий и метод:

import { Output, EventEmitter } from '@angular/core';

export class CustomControl .... {
    @Output()
    public stateChange = new EventEmitter<boolean>();

    public validate(value: string): void {
        let valid: boolean | undefined;

        // Ваша валидация `value`, например:
        if (/\d/.test(value)) {
            valid = true;
        } else {
            valid = false;
        }

        this.stateChange.emit(valid);
    }
}

Далее делаем подписку на событие дочернего компонента:

<app-custom-control
    [formControlName]="'password'" 
    (stateChange)="stateChange($event)">
</app-custom-control>

В родительском компоненте, который в шаблоне содержит app-custom-control создаем метод:

public stateChange(valid: boolean): void {
    if (valid) {
        // контрол прошел валидацию
    } else {
        // не прошел
    }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.