【问题标题】:Why does my project result in the "More than one component matched on this element." error?为什么我的项目会导致“在此元素上匹配多个组件”。错误?
【发布时间】:2019-07-02 00:58:37
【问题描述】:

我在 StackBlitz 中有以下项目:

https://stackblitz.com/github/nickhodges/PhillyCCTodoApp/tree/Step20

我收到此错误:

Template parse errors:
More than one component matched on this element.
Make sure that only one component's selector can match a given element.

我用谷歌搜索了我的小心脏,但似乎找不到解决方案。

这个错误是什么意思,我该如何解决?

我应该注意,该错误仅发生在 StackBlitz 中,而不发生在我的本地计算机上。

【问题讨论】:

    标签: angular stackblitz


    【解决方案1】:

    在 Angular 中,我们不能在同一个元素上拥有两个组件

    错误表明 Angular 编译器发现了两个与 <mat-form-field 元素匹配的组件。

    它还指向它发生的模块。

    ng:///InputControlsModule/EmailInputComponent.html@1:2

    并打印那些冲突的组件:

    MatFormField,MatFormField

    由于这些组件具有相同的名称,因此只能表示一个:

    您以某种方式在InputControlsModule 中导入了两个导出MatFormField 指令的不同模块。

    查看您的模块:

    @NgModule({
      imports: [
        ...
        MatFormFieldModule,
        MatInputModule
      ],
      ...
    })
    export class InputControlsModule {}
    

    我注意到您导入了 MatFormFieldModuleMatInputModule 导出 MatFormFieldModule(https://github.com/angular/material2/blob/8050f633b56b6c048fc72dad2ab79304afdfad19/src/lib/input/input-module.ts#L29)

    但你可能会想:我阅读了文档,这应该不是问题,因为 Angular 会缓存一次导入的模块:

    What if I import the same module twice?

    现在,看看你是如何导入这些模块的:

    import { ...MatInputModule} from '@angular/material';
                                            |
                                    material.umd.js
    
    import { MatFormFieldModule } from '@angular/material/form-field';
                                                      |
                                             material-form-field.umd.js
    

    你可以猜到,因为这些模块来自不同的 js 文件,它们是不同的。

    所以为了修复它,你应该从同一个包中导入它们。

    import {
      ...
      MatInputModule,
      MatFormFieldModule 
    } from '@angular/material';
    

    但由于MatInputModule 已经导出MatFormFieldModule,您不需要导入它。

    Forked Stackblitz

    【讨论】:

      【解决方案2】:

      以防万一其他人在测试中遇到这种情况,我在同一个测试中意外地以两种不同的方式模拟了同一个组件。两个模拟都有一个选择器。测试失败的输出并不清楚冲突的起源。我花了很多时间试图找出答案。希望这可以为其他人节省一两个小时:|

      【讨论】:

      • 非常感谢!我试图清除一些测试,但没有看到我想模拟的组件已经在导入中......
      猜你喜欢
      • 1970-01-01
      • 2018-12-21
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多