F
F
FNY3PM2021-03-29 18:55:26
Angular
FNY3PM, 2021-03-29 18:55:26

Why is custom FormControl validation not working?

I have a parent component with a form:

<form [formGroup]="authFormGroup">
        <p>
            <small class="title">Логин</small>
            <app-input [phone]="true" formControlName="login"></app-input>
            <small class="error">Введите корректный логин</small>
        </p>
    </form>


In which the form is created and the FormControl is added:
this.authFormGroup = new FormGroup({
      'login': new FormControl('', [Validators.required, Validators.minLength(5)])
    })


The login FormControl is a separate text component that I coded to work like a FormControl.
@Component({
  selector: 'app-input',
  templateUrl: './input.component.html',
  styleUrls: ['./input.component.sass'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => InputComponent),
      multi: true
    }
  ]
})
export class InputComponent implements OnInit, ControlValueAccessor {

  @Input('phone') isShowingPhone: boolean = false
  value: string = ''

  constructor() {
  }


  onChange: any = () => { };
  onTouched: any = () => { };

  writeValue(value: string): void {
    this.value = value
  }
  registerOnChange(fn: any): void {
    this.onChange = fn
  }
  registerOnTouched(fn: any): void {
    this.onTouched = fn
  }

  ngOnInit(): void {
  }

  update(): void {
    this.onChange(this.value)
  }


}


And everything works, except for the validators. The input element inside my app-input component gets ng-touched and ng-dirty added, but how can I add ng-invalid to it if the validators from the form group worked?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sun_Day, 2021-03-30
@Sun_Day

Your control by default should have status: valid/invalid and errors: null if validation is not set, and errors: {object with validators you set here} if validation is set.
1) Show the input template.
2) Perhaps you are looking at the validation error in the wrong place, or judging by your template, you don’t look at it at all and it’s not clear what behavior you expect. Judging by what you threw off, the status of your validation can be monitored along this path:

{{ authFormGroup.controls.login.errors?.minlength.requiredLength }}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question