【问题标题】:Is there a way to use a mat-autocomplete where the corresponding input is in its parent component?有没有办法在其父组件中使用相应输入的垫子自动完成功能?
【发布时间】:2020-07-16 04:46:07
【问题描述】:

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

使用常规数据列表元素

parent.component.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>

【问题讨论】:

    标签: angular typescript angular-material autocomplete mat-autocomplete


    【解决方案1】:

    我登陆这里是因为我正在寻找“错误:找不到名称'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

    希望对你有帮助:)

    【讨论】:

    • 是的,我认为这主要是一个输出,因为父组件需要引用子组件中的元素
    • 即使我已经导入它也会出错。谢谢
    • @MindRoasterMir 我会提到这也发生在我身上。一旦我重新启动构建,它就开始工作了。
    猜你喜欢
    • 1970-01-01
    • 2022-08-12
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多