Why does my project result in the "More than one component matched on this element." error?

Nick Hodges picture Nick Hodges · Dec 23, 2018 · Viewed 18.3k times · Source

I have the following project in a StackBlitz:

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

I get this error:

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

I have googled my little heart out, but can't seem to find a solution.

What does this error mean and how do I fix it?

I should note that the error only occurs in StackBlitz and not on my local machine.

Answer

yurzui picture yurzui · Dec 23, 2018

In Angular we can't have two components on the same element.

The error states that Angular compiler found two components that match <mat-form-field element.

Also it points to the module where it happened.

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

And prints those conflicting components:

MatFormField,MatFormField

Since those components have the same name it can mean only one:

You somehow imported in InputControlsModule two different modules that export MatFormField directive.

Looking at your module:

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

I noticed that you imported MatFormFieldModule and also MatInputModule that export MatFormFieldModule(https://github.com/angular/material2/blob/8050f633b56b6c048fc72dad2ab79304afdfad19/src/lib/input/input-module.ts#L29)

But you may think: I read documentation and it shouldn't be a problem since Angular caches once imported module:

What if I import the same module twice?

Now, take a look at how you imports those modules:

import { ...MatInputModule} from '@angular/material';
                                        |
                                material.umd.js

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

As you can guess since those modules from different js files they are different.

So in order to fix it you should import them from the same bundle.

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

But since MatInputModule already exports MatFormFieldModule you do not need to import it.

Forked Stackblitz