在我的自定义输入组件上使用[matAutocomplete] [英] Use [matAutocomplete] on my custom input component
问题描述
因此,我用自定义样式制作了自己的 lib-input
组件,它看起来像这样:
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>
现在,我想将此 lib-input
及其自定义样式用于使用自动完成功能的输入字段.
Now I want to use this lib-input
with its custom styles for an input field that uses autocomplete.
类似这样的东西:
<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] ...>
无效,因为属性matAutocomplete不由任何适用的指令或lib-input元素提供
,这很有意义,因为我的 lib-input
没有 matAutocomplete
作为输入.
<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.
有什么解决方法吗?我不想制作使用< input [matAutocomplete]>
的单独组件,因为我的自定义样式以及 lib-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.
推荐答案
您实际上可以只将matAutocomplete传递给您的自定义输入.因此,在您的 lib-input.component.ts
中:
You can actually just pass the matAutocomplete through to your custom input. So in your lib-input.component.ts
:
@Input() matAutocomplete: MatAutocomplete;
,然后将其传递给 lib-input.component.html
中的< input>
.唯一的缺点是,如果您不总是希望将 lib-input
与自动完成功能配合使用,则最终会出现一些难看的代码重复:
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>
这篇关于在我的自定义输入组件上使用[matAutocomplete]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!