简体   繁体   English

使用 angular 表单 ControlValueAccessor 和 mat-autocomplete

[英]Using angular form ControlValueAccessor and mat-autocomplete

I have a problem that perhaps someone have encountered before..我有一个问题,也许有人以前遇到过..

  <input matInput required type="text" [value]="ngControl.value.name"
    [placeholder]="costCenterTranslations.company | translate" [formControl]="ngControl?.control"
    [matAutocomplete]="companyAutoComplete" (input)="onChanged($event.target.value)"
    (blur)="onTouched($event.target.value)" />
  <mat-autocomplete #companyAutoComplete="matAutocomplete" (optionSelected)="onChanged($event.option.value)"
    [displayWith]="displayFn.bind(this)">
    <mat-option *ngFor="let company of companies$ | async" [value]="company">
      <span>{{ company.name }}</span>
    </mat-option>
  </mat-autocomplete>
constructor(
    private readonly _translation: TranslationService<Translations>,
    @Optional() @Self() public ngControl: NgControl,
  ) {
    if (this.ngControl != null) {
      // Setting the value accessor directly (instead of using the providers) to avoid running into a circular import.
      this.ngControl.valueAccessor = this;
    }
  }

  onTouched = (_value?: any) => {
    console.log('onTouched', _value);

  };
  onChanged = (_value?: any) => {
    console.log('onChanged', _value);
  }

  writeValue(company: Company): void {
    this.ngControl.control?.setValue(company);
  }

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

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

  displayFn(company?: Company) {
    console.log('displayFn:', company && company ? company.name : '');
    return company && company ? company.name : '';
  }

So the problem is that I want the control to pass only the company.id.. but none of the registerOn* functions are triggered.. so the whole object is passed.. ideas on why?所以问题是我希望控件仅传递 company.id.. 但没有触发任何 registerOn* 函数.. 所以整个 object 都传递了.. 关于为什么的想法?

The displayWith will map to control.value so it needs to return the company id. displayWith会将 map 转换为 control.value,因此它需要返回公司 ID。

Then to get the company.name as input value the <mat-option [value]="company.name">然后获取company.name作为输入值<mat-option [value]="company.name">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM