首页 > 解决方案 > 有没有办法在其父组件中使用相应输入的垫子自动完成功能?

问题描述

这适用于常规 datalist 元素,其中list="target"输入元素上的 可以id="target"在子组件中找到 。我试图找出一种方法来使用材料自动完成组件来做到这一点。

使用常规 datalist 元素

父组件.html

 <input type="text" list="target">
 <app-child></app-child>

child.component.html

<datalist id="target">
    <option *ngFor="let option of options" [value]="option.name"></option>
</datalist>

我整天都在尝试实现此功能,但通常会遇到以下两个错误之一:

Error: Attempting to open an undefined instance of `mat-autocomplete`. Make sure that the id passed to the `matAutocomplete` is correct and that you're attempting to open it after the ngAfterContentInit hook.

或者

Error: Export of name 'matAutocomplete' not found!

使用 Mat-Form-Field 和 Mat-Autocomplete

mat-parent.component.html

<mat-form-field>
    <input type="text" matInput [matAutocomplete]="auto">
</mat-form-field>
<app-mat-child></app-mat-child>

mat-child.component.html

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

标签: angulartypescriptangular-materialautocompletemat-autocomplete

解决方案


我登陆这里是因为我正在寻找“错误:找不到名称'matAutocomplete'的导出!” 细绳。我通过导入 MatAutocompleteModule 在我的项目中修复了它。因此,在您的组件的module.ts中,您需要添加以下内容:

import { MatAutocompleteModule } from '@angular/material/autocomplete';

(then scroll down to your imports array)

imports: [
  MatAutocompleteModule
]

关于主要问题,我本人对 Angular 有点陌生,但是如果您想将文本从父级传递给子级,则需要使用“输入”。

我建议您阅读文档的相应部分,我无法比这更好地解释它:https ://angular.io/guide/template-syntax#how-to-use-input

我希望它有帮助:)


推荐阅读