格式化角度材料自动完成输入

时间:2018-09-27 08:09:49

标签: angular autocomplete angular-material

我的任务是使用Angular Material自动完成和数字格式构建输入。对于项目,我构建了一个数字格式程序,该格式程序可用于许多输入字段。

问题:Angular不允许一个控件使用多个ControlValueAccessor。 因此,我必须在格式CVA和自动完成CVA之间进行选择。

我尝试了一种其他隐藏的自动完成输入的解决方法。 onFocus / onBlur打开/关闭隐藏输入的自动完成框,自动完成的change事件将所选值写入可见输入。但是,通过函数调用将其打开时,Angular Material Autocomplete不会触发changeevent。

我可以从手动打开的自动完成功能中捕获更改的事件吗? 您知道我的问题有更好的解决方法吗?

这是我目前的尝试:

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { FormBuilderService } from '../../../services/form-builder.service';
import { FormMetadataService } from '../../../services/form-metadata.service';
import { CustomAutocompleteComponent } from './custom-autocomplete.component';
import { MatAutocompleteTrigger, MatAutocomplete, MatAutocompleteSelectedEvent } from '@angular/material';

@Component({
  selector: 'app-custom-autocomplete-numeric',
  templateUrl: './custom-autocomplete-numeric.component.html'
})
export class CustomAutocompleteNumericComponent extends CustomAutocompleteComponent implements OnInit {
  @ViewChild('faketrigger', { read: MatAutocompleteTrigger }) faketrigger: MatAutocompleteTrigger;
  @ViewChild('faketrigger') faketextbox: ElementRef;
  @ViewChild('auto', { read: MatAutocomplete }) auto: MatAutocomplete;
  @ViewChild('textbox') textbox: ElementRef;

  constructor(
    formDataService: FormBuilderService,
    metadataService: FormMetadataService) {
    super(formDataService, metadataService);
  }

  ngOnInit() {
    super.ngOnInit();
    this.auto.optionSelected.subscribe(_ => this.setSelectedValue(_));
  }

  private setSelectedValue(event: MatAutocompleteSelectedEvent): void {
    this.textbox.nativeElement.value = event.option.value;
  }

  public openAutocomplete(): void {
    setTimeout(() => {
    this.faketrigger.openPanel();
    }, 200);
  }
  public closeAutocomplete(): void {
    this.faketrigger.closePanel();
  }

}
<div>
  <mat-form-field>
    <span *ngIf="prefix" matPrefix>{{prefix}} &nbsp;</span>
    <input class="numeric" [placeholder]="customPlaceholder" [formControl]="customFormControl" matInput #textbox
      [appHelp]="name" [appFormat]="customFormControl" (focus)="openAutocomplete()" (blur)="closeAutocomplete()">
    <span *ngIf="suffix" matSuffix>&nbsp;{{suffix}}</span>
  </mat-form-field>
  
  <mat-form-field>
    <input [matAutocomplete]="auto" #faketrigger style="display: block" matInput>
    <mat-autocomplete #auto>
      <mat-option *ngFor="let o of options" [value]="o.Value" [attr.image]="o.Key">{{o.Value}}</mat-option>
    </mat-autocomplete>
  </mat-form-field>
</div>

0 个答案:

没有答案