Use [matAutocomplete] on my custom input component

蹲街弑〆低调 提交于 2020-12-14 06:22:04

问题


So I made my own lib-input component with custom styles that looks something like this:

<div class="input">
    <mat-form-field appearance="outline">
        <input matInput [type]="type" placeholder="{{placeholder}}" [(ngModel)]="input" (input)="onChange()">
        <ng-content></ng-content>
    </mat-form-field>
</div>

Now I want to use this lib-input with its custom styles for an input field that uses autocomplete.

Something like this:

<mat-form-field>
  <lib-input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto">
</mat-form-field>

<mat-autocomplete #auto="matAutocomplete">
  <mat-option *ngFor="let option of options" [value]="option">{{option}}</mat-option>
</mat-autocomplete>

<lib-input [matAutocomplete] ...> doesn't work though, because Property matAutocomplete is not provided by any applicable directives nor by lib-input element, which makes sense, since my lib-input doesn't have matAutocomplete as Input.

Is there any workaround for this? I don't want to make a separate component that uses <input [matAutocomplete]> because I would have duplicate code for my custom styles, as well as the functionality my lib-input field has.


回答1:


You can actually just pass the matAutocomplete through to your custom input. So in your lib-input.component.ts:

@Input() matAutocomplete: MatAutocomplete;

and then pass this to your <input> in the lib-input.component.html. The only downside is, that if you don't always want to use the lib-input with autocomplete, you kind of end up with a bit of ugly code repetition:

<div class="input">
  <mat-form-field appearance="outline">
    <input *ngIf="matAutocomplete" matInput [type]="type" placeholder="{{placeholder}}" [(ngModel)]="input" (input)="onChange()" [matAutocomplete]="matAutocomplete">
    <input *ngIf="!matAutocomplete" matInput [type]="type" placeholder="{{placeholder}}" [(ngModel)]="input" (input)="onChange()">
    <ng-content></ng-content>
  </mat-form-field>
</div>



回答2:


The answer from tommueller is fine.

In my case my custom input implemented the ControlValueAccessor Interface and I needed to subscribe to MatAutocomple.optionSelected to trigger the registered onChange.

  ngAfterViewInit(): void {
    this.matAutocomplete?.optionSelected.subscribe(
      (event: MatAutocompleteActivatedEvent) => {
        this.onChange(event?.option?.value);
      }
    );
  }



回答3:


try this

in your component create new input property

@Input() matAutocomplete: string;

then pass it to your input , so your input will be like this

<input ..... [matAutocomplete]="matAutocomplete"/>



来源:https://stackoverflow.com/questions/58872590/use-matautocomplete-on-my-custom-input-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!