Answers for "ControlValueAccessor"

0

ControlValueAccessor

@Component({
  selector: 'my-list',
  templateUrl: 'my-list.html',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      multi:true,
      useExisting: EmploymentStatusListComponent
    }
  ]
  })
export class MyListComponent implements OnInit,ControlValueAccessor/*,AfterViewInit, Validator*/  {

  /** 
   * Comments and observations
   * ViewChild is sometimes accessible only after AfterViewInit
   * DISABLE:
   * 1)
   * setDisabledState() is called if on the parent comp. we:
   *              - innitiate form with FormControl({value: '', disabled: true})
   *              - call this.form.get('controlName').disable()
   * 2)
   * Otherwise we can disable through angular input property @Input() disabled? : boolean 
   * And then use it on the template
   *            <ng-select ... [disabled] = "disabled ? true : null" .... > 
   * 
  */

  @ViewChild('selectComponent', { static: false }) selectComponent: ElementRef | undefined;
  //@ViewChild(NgSelectComponent) selectComponent?: NgSelectComponent;
  @Input() statusList: any;
  @Input() disabled? : boolean = false;
  //touched = false;
  selectedOption: any;

  constructor(private _renderer: Renderer2) { }
  /*
  ngAfterViewInit(): void {
    console.log('ngAfterViewInit', this.selectComponent);
  }
*/
  onChange = ( _: any) => {};
  onTouched = () => {};

  writeValue(obj: any): void {
    if(obj ){
      //this.selectComponent.select(obj);
      this.selectedOption = obj;
      console.log('comp',obj);
    }
    console.log('comp',obj);
  }

  ngAfterInit(){

  }

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

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

  setDisabledState(isDisabled: boolean): void {
    console.log('---setDisabledState');
    //this._renderer.setProperty(this.selectComponent?.nativeElement, 'disabled', isDisabled);
    this.disabled = isDisabled;
  }

  onSelectionChange(event$: any){
    if(event$){
      this.onChange(event$);
    }
    this.onTouched();
  }

  ngOnInit(): void {
    //console.log('init', this.selectComponent);
  }
/*
  validate(control: AbstractControl): ValidationErrors | null {
    if(control.value === undefined){
      return {

      }
    }
  }*/

}
Posted by: Guest on September-22-2021

Code answers related to "ControlValueAccessor"

Browse Popular Code Answers by Language