Angular ngx-mat-select-search Custom Component

前端 未结 1 1329
无人及你
无人及你 2020-12-30 14:39

I am trying to use the ngx-mat-select-search component to put a mat-select style dropdown menu with a search bar in my application. https://www.npmjs.com/package/ngx-mat-se

相关标签:
1条回答
  • 2020-12-30 15:02

    you can get the value of the selected option by having your SiteDropdownComponent implement the ControlValueAccessor interface as follows, resulting in your SiteDropdownComponent behaving as a form control and allowing to access the value with e.g. <app-site-dropdown formControlName="site"></app-site-dropdown>:

    ...
    import { forwardRef } from '@angular/core';
    import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
    
    @Component({
      selector: 'app-site-dropdown',
      template: ...
      providers: [
        {
          provide: NG_VALUE_ACCESSOR,
          useExisting: forwardRef(() => SiteDropdownComponent),
          multi: true
        }
      ],
    })
    export class SiteDropdownComponent implements OnInit, OnDestroy, AfterViewInit, ControlValueAccessor {
      ...
    
      onChange: Function = (_: any) => {};
      onTouched: Function = (_: any) => {};
    
      constructor() { }
    
      ngOnInit() {
        ...
        // call this.onChange to notify the parent component that the value has changed
        this.siteCtrl.valueChanges
          .pipe(takeUntil(this.onDestroy))
          .subscribe(value => this.onChange(value))
      }
    
      writeValue(value: string) {
        // set the value of siteCtrl when the value is set from outside the component
        this.siteCtrl.setValue(value);
      }
    
      registerOnChange(fn: Function) {
        this.onChange = fn;
      }
    
      registerOnTouched(fn: Function) {
        this.onTouched = fn;
      }
    
    }
    

    See e.g. https://github.com/bithost-gmbh/ngx-mat-select-search/blob/d7ea78d511bbec45143c58c855f013a44d0d5055/src/app/mat-select-search/mat-select-search.component.ts#L134

    0 讨论(0)
提交回复
热议问题