custom control value accessor not showing validation

92 Views Asked by At

When i set validation required for this form control . its not showing validation required error msg


@Component({
  selector: 'app-dropdown-search',
  templateUrl: './dropdown-search.component.html',
  styleUrls: ['./dropdown-search.component.scss'],
})
export class DropdownSearchComponent implements OnInit, ControlValueAccessor {
  @Input() itemSource: any[] = [
    { Id: 1, Value: 'one' },
    { Id: 2, Value: 'two' },
  ];

  searchText: string = '';
  selectedOption: any;
  isDisabled: boolean = false;
  onChange: any = () => {};
  onTouched: any = () => {};

  filteredOptions$!: Observable<any[]>;
  private searchTextSubject = new BehaviorSubject<string>('');

  constructor(@Optional() @Self() public ngControl: NgControl) {
    if (this.ngControl) {
      this.ngControl.valueAccessor = this;
    }
  }

  ngOnInit(): void {
    this.filteredOptions$ = this.searchTextSubject.pipe(
      debounceTime(100),
      distinctUntilChanged(),
      map((text) => this.filterOptions(text))
    );

    // If initial value is provided, select the corresponding option
    if (this.ngControl && this.ngControl.value) {
      this.selectedOption = this.itemSource.find(
        (item) => item.Id === this.ngControl.value
      );
      this.searchText = this.selectedOption ? this.selectedOption.Value : '';
    }
  }

  writeValue(value: any): void {
    if (this.ngControl) {
      this.selectedOption = this.itemSource.find((item) => item.Id === value);
      this.searchText = this.selectedOption ? this.selectedOption.Value : '';
    }
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

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

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

  selectOption(option: any): void {
    this.selectedOption = option;
    this.searchText = option.Value;
    this.onChange(option.Id);
    this.onTouched();
  }

  onSearchTextChange(text: string): void {
    this.searchTextSubject.next(text);
  }

  trackByFn(index: number, item: any) {
    return item.Id;
  }

  filterOptions(text: string): any[] {
    if (!text || typeof text !== 'string') {
      return [];
    }

    text = text.trim();

    if (text === '') {
      return [];
    }
    return this.itemSource.filter((item) =>
      item.Value.toLowerCase().includes(text.toLowerCase())
    );
  }
}

<mat-form-field appearance="outline" class="form-field">
  <mat-label>Employee</mat-label>
  <input
    matInput
    [placeholder]="'Search and Select...'"
    [(ngModel)]="searchText"
    [matAutocomplete]="auto"
    [disabled]="isDisabled"
    (ngModelChange)="onSearchTextChange($event)"
  />
  <mat-autocomplete #auto="matAutocomplete">
    <mat-option
      *ngFor="let option of filteredOptions$ | async; trackBy: trackByFn"
      [value]="option"
      (click)="selectOption(option)"
    >
      {{ option.Value }}
    </mat-option>
  </mat-autocomplete>
  <mat-error *ngIf="ngControl?.hasError('required')">Required</mat-error>
  <mat-error *ngIf="ngControl?.hasError('invalidOption')"
    >Invalid option</mat-error
  >
</mat-form-field>


This above is my custom control and I'm setting validation in parent form like below

this.frmGroup = this.fb.group({ name: [null, Validators.required], isLocked: [{ value: false }], });

here i define validators required for above custom formcontrol

<app-dropdown-search formControlName="name"></app-dropdown-search>

im expecting Validation requred should be show if that control is invalid or touched

0

There are 0 best solutions below