CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error
Asked Answered
H

22

213

I just upgraded from Angular 2 rc4 to rc6 and having troubles doing so.

I see the following error on my console:

Unhandled Promise rejection: Template parse errors:
'cl-header' is not a known element:
1. If 'cl-header' is an Angular component, then verify that it is part of this module.
2. If 'cl-header' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message. ("<main>
    [ERROR ->]<cl-header>Loading Header...</cl-header>
    <div class="container-fluid">
      <cl-feedbackcontai"): AppComponent@1:4

Here is my Header Component:

import { Component } from '@angular/core';
import { Router } from '@angular/router';

// own service
import { AuthenticationService } from '../../../services/authentication/authentication.service.ts';

import '../../../../../public/css/styles.css';

@Component({
  selector: 'cl-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent { // more code here... }

Here is my Header Module:

import { NgModule, CUSTOM_ELEMENTS_SCHEMA }      from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule }      from '@angular/common';
import { FormsModule }      from '@angular/forms';

import { HeaderComponent }  from './../../../components/util_components/header/header.component.ts';

@NgModule({
    declarations: [ HeaderComponent ],
    bootstrap:    [ HeaderComponent ],
    imports: [ RouterModule, CommonModule, FormsModule ],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class HeaderModule { }

I created a wrapper module called util module which imports the HeaderModule:

import { NgModule }      from '@angular/core';

import {HeaderModule} from "./header/header.module";
// ...

@NgModule({
    declarations: [ ],
    bootstrap:    [ ],
    imports: [ HeaderModule]
})
export class UtilModule { }

Which is finally imported by the AppModule:

import { NgModule }      from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';

import {UtilModule} from "./modules/util_modules/util.module";
import {RoutingModule} from "./modules/routing_modules/routing.module";

@NgModule({
    bootstrap: [AppComponent],
    declarations: [AppComponent],
    imports: [BrowserModule, UtilModule, RoutingModule]
})
export class AppModule { }

To my understanding I am following the instructions of the error message using the SCHEMA to surpress the error. But it seems not to work. What am I doing wrong? (I hope its nothing obvious I just don't see at the moment. Been spending the past 6 hours upgrading to this version...)

Hanser answered 10/9, 2016 at 16:22 Comment(3)
If you add it to your AppModule do you still have to add it to your component?Grout
same here, for me just adding " schemas: [CUSTOM_ELEMENTS_SCHEMA ] " worked like a charm. Thank you:)Photophilous
It'd be helpful if you added your "Fix" as an Answer to this question, so that it is clear to others who come across your question as to exactly how they can benefit from using your solution :]Laellaertes
H
173

This is fixed by:

a) adding schemas: [ CUSTOM_ELEMENTS_SCHEMA ] to every component or

b) adding

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

and

schemas: [
  CUSTOM_ELEMENTS_SCHEMA
],

to your module.

Hanser answered 3/11, 2016 at 17:23 Comment(9)
do not forget to declare it ... it's located in @angular/core. Something like that should fit:import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';Tease
This post could help with the procedure to follow: medium.com/google-developer-experts/…Hinshaw
adding schemas: [ CUSTOM_ELEMENTS_SCHEMA ] to EVERY component, did the trick! Thanks!Potato
schemas doesn't exist in angular 9Burrton
No; didn't solve my problem... maybe its an Angular 11 thingEcotone
Not sure where it would go in each component. You would just need to put it in the module, I believe.Fokine
I was importing it from @angular/compiler that was my problemDeuced
I tried with this answer but my problem didn't solve. I'm working with angular 13Uterus
This will get rid of the error, but it will also introduce a problem. The compiler will stop checking if the components actually exist that is being referenced on the page. Typos won't be picked up immediately. This is a quick fix, but not solving the root cause.Mclendon
C
140

Just wanted to add a little bit more on this.

With the new angular 2.0.0 final release (sept 14, 2016), if you use custom html tags then it will report that Template parse errors. A custom tag is a tag you use in your HTML that's not one of these tags.

It looks like the line schemas: [ CUSTOM_ELEMENTS_SCHEMA ] need to be added to each component where you are using custom HTML tags.

EDIT: The schemas declaration needs to be in a @NgModule decorator. The example below shows a custom module with a custom component CustomComponent which allows any html tag in the html template for that one component.

custom.module.ts

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';

import { CustomComponent } from './custom.component';

@NgModule({
  declarations: [ CustomComponent ],
  exports: [ CustomComponent ],
  imports: [ CommonModule ],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class CustomModule {}

custom.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-custom-component',
  templateUrl: 'custom.component.html'
})
export class CustomComponent implements OnInit {
  constructor () {}
  ngOnInit () {}
}

custom.component.html

In here you can use any HTML tag you want.

<div class="container">
  <boogey-man></boogey-man>
  <my-minion class="one-eyed">
    <job class="plumber"></job>
  </my-minion>
</div>
Crandall answered 18/9, 2016 at 3:16 Comment(13)
I have a very simple app that has multiple components in a single module. I have added it to my module... I still get errors ...Demarcate
If you create a plunkr or post some of the code, particularly the components and modules you are having problems into a separate question, I can take a look at it and help you.Crandall
Thanks Caleb. I was getting the errors when running a simple test. I figured it out though... I was not adding the CUSTOM_ELEMENTS_SCHEMA to my unit test fake module. As soon as I did that, it stopped complaining.Demarcate
Is there a way to define custom elements that are allowed? Using CUSTOM_ELEMENTS_SCHEMA could lead to errors that are hard to find, but I would like to use custom element names for ng-content sections in my controls without those specific element names causing errors and without creating components for them that would just be ng-content...Banquette
@JasonGoemaat, looks like currently CUSTOM_ELEMENTS_SCHEMA is an all or nothing per component schema. The good news is that according to this thread it looks like the angular team are planning a more flexible schema in the near future.Crandall
@Crandall can you please provide a quick code example of what you mean by It looks like the line schemas: [ CUSTOM_ELEMENTS_SCHEMA ] need to be added to each component where you are using HTML tags? It looks like the Component decorator isn't accepting a schemas parameter.Laellaertes
Hey @DannyBullis, instead of the Component decorator, it's found in the NgModule decorator. You'll need to create a module for that component and then you can specify the schema there. Link to docs and an example.Crandall
@Crandall can you edit your answer to reflect the last comment? Looks misleading at the moment.Shrovetide
@Shrovetide Good call. Updated my answer, hopefully that's more clear on how to use it.Crandall
This would affect every component declared in this module.Schramm
Is it possible to name the custom elements? So that you still get the errors if you make typo'sQuarrelsome
It worked for me, I just made the changes and then restarted the vscode. Thanks !Jordanna
Gives an opportunity to add schemas to global appConfig?Fortuneteller
K
58

This can also come up when running unit tests if you are testing a component with custom elements. In that case custom_elements_schema needs to be added to the testingModule that gets setup at the beginning of the .spec.ts file for that component. Here is an example of how the header.component.spec.ts setup would begin:

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

describe('HeaderComponent', () => {
  let component: HeaderComponent;
  let fixture: ComponentFixture<HeaderComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [PrizeAddComponent],
      schemas: [
        CUSTOM_ELEMENTS_SCHEMA
      ],
    })
      .compileComponents();
  }));
Kumar answered 17/4, 2018 at 22:35 Comment(1)
Thanks! Took me much too #&@% long to find this.Moreta
F
31

Add the following under @NgModule({})in 'app.module.ts' :

import {CUSTOM_ELEMENTS_SCHEMA} from `@angular/core`;

and then

schemas: [
    CUSTOM_ELEMENTS_SCHEMA
]

Your 'app.module.ts' should look like this:

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

@NgModule({
  declarations: [],
  imports: [],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }
Ferris answered 27/12, 2016 at 13:26 Comment(1)
but now your whole app is allowing custom tags.Schramm
C
13

It didn't work for me either. I changed

CUSTOM_ELEMENTS_SCHEMA

for

NO_ERRORS_SCHEMA

which was suggested in this article: https://scotch.io/tutorials/angular-2-transclusion-using-ng-content

Now it works.

Concern answered 16/11, 2016 at 16:43 Comment(4)
Nice! It worked for me. I wanted to add XML elements on my component HTML and i was getting errors. Thanks a lotEnt
was serving angular elements within angular elements within angular elements (Angular 8) adding CUSTOM_ELEMENTS_SCHEMA did not help but NO_ERRORS_SCHEMA did do the trick and all the nesting of standalone angular elements now works like a charmCondiment
This worked for me on TestBed. Element was working fine but test was failing. Added schemas: [NO_ERRORS_SCHEMA], and it's all good.Dangelo
Both are not worked for meUterus
A
12

With components containing Angular Material, a similar error came up with my unit tests. As per @Dan Stirling-Talbert's answer above, added this to my component .spec file and the error was cleared from my unit tests.

Import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'

Then add the schema in the generated beforeEach() statement:

beforeEach(asyn(() => {
    declarations: [ AboutComponent ],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
.compileComponents();
}));

My Karma error was: If 'mat-panel-title' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

Abra answered 31/5, 2019 at 15:5 Comment(0)
G
11

util.component.ts

@Component({
    selector: 'app-logout',
    template: `<button class="btn btn-primary"(click)="logout()">Logout</button>`
})
export class LogoutComponent{}

util.module.ts

@NgModule({
    imports: [...],
    exports: [
        LogoutComponent
    ],
    declarations: [LogoutComponent]
})
export class AccountModule{};

LogoutComponent Needs to be exported

dashboard.module.ts
import AccountModule in module where we want to use <app-logout> import { AccountModule } from 'util.module';

@NgModule({
  imports: [
    CommonModule, AccountModule
  ],
  declarations: [DashboardComponent]
})
export class DashboardModule { }

dashboard.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-dashboard',
  template: `<div><app-logout></app-logout></div>`
})
export class DashboardComponent implements OnInit {
  constructor() {}
  ngOnInit() {}
}

I am not required to import and use CUSTOM_ELEMENTS_SCHEMA.
however its not working when dashboard.module is lazy loaded.
When using CUSTOM_ELEMENTS_SCHEMA in case of lazy loading, error is suppressed but the component is not added to dom.

Goring answered 6/1, 2017 at 11:22 Comment(5)
idem +1 no more error, but no dom update anymore, this workaround for trying to make work those selectors with '-' is ####!!!&&ù*$Liberalize
Thanks a lot , after I week , i found out that it can't work with lazy loading in ionicEwall
@Goring - your solution is 100% accurate, 1) need to add to the export and 2) no need of custom_elements_schemaGiovanna
I had the same error and I set my components in each module where I needed in declarations clausule. I Didn't use CUSTOM_ELEMENTS_SCHEMA and worked.Swiger
Thanks man... 100% working. My Angular version is 11.Munn
M
5

Just read this post and according to the angular 2 docs:

export CUSTOM_ELEMENTS_SCHEMA
Defines a schema that will allow:

any non-Angular elements with a - in their name,
any properties on elements with a - in their name which is the common rule for custom elements.

So just in case anyone runs into this problem, once you have added CUSTOM_ELEMENTS_SCHEMA to your NgModule, make sure that whatever new custom element you use has a 'dash' in its name eg. or etc.

Mond answered 3/2, 2017 at 8:4 Comment(2)
A dash in the name? Why impose such a stupid convention?Sika
I only run into this when I just started using lazy loading in Ionic3 and only when I try to build for the web. Could please post the link to the docs you mention. Thank you.Sika
B
5

This is rather long post and it gives a more detailed explanation of the issue.

The problem (in my case) comes when you have Multi Slot Content Projection

See also content projection for more info.

For example If you have a component which looks like this:

html file:

 <div>
  <span>
    <ng-content select="my-component-header">
      <!-- optional header slot here -->
    </ng-content>
  </span>

  <div class="my-component-content">
    <ng-content>
      <!-- content slot here -->
    </ng-content>
  </div>
</div>

ts file:

@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss'],
})
export class MyComponent {    
}

And you want to use it like:

<my-component>
  <my-component-header>
    <!-- this is optional --> 
    <p>html content here</p>
  </my-component-header>


  <p>blabla content</p>
  <!-- other html -->
</my-component>

And then you get template parse errors that is not a known Angular component and the matter of fact it isn't - it is just a reference to an ng-content in your component:

And then the simplest fix is adding

schemas: [
    CUSTOM_ELEMENTS_SCHEMA
],

... to your app.module.ts


But there is an easy and clean approach to this problem - instead of using <my-component-header> to insert html in the slot there - you can use a class name for this task like this:

html file:

 <div>
  <span>
    <ng-content select=".my-component-header">  // <--- Look Here :)
      <!-- optional header slot here -->
    </ng-content>
  </span>

  <div class="my-component-content">
    <ng-content>
      <!-- content slot here -->
    </ng-content>
  </div>
</div>

And you want to use it like:

<my-component>
  <span class="my-component-header">  // <--- Look Here :) 
     <!-- this is optional --> 
    <p>html content here</p>
  </span>


  <p>blabla content</p>
  <!-- other html -->
</my-component>

So ... no more components that do not exist so there are no problems in that, no errors, no need for CUSTOM_ELEMENTS_SCHEMA in app.module.ts

So If You were like me and did not want to add CUSTOM_ELEMENTS_SCHEMA to the module - using your component this way does not generates errors and is more clear.

For more info about this issue - https://github.com/angular/angular/issues/11251

For more info about Angular content projection - https://blog.angular-university.io/angular-ng-content/

You can see also https://scotch.io/tutorials/angular-2-transclusion-using-ng-content

Bicuspid answered 1/10, 2018 at 11:8 Comment(1)
this was just what I was looking for, thanks for sharing!Handspike
S
4

solved this problem in the /app/app.module.ts file

import your component and declare it

import { MyComponent } from './home-about-me/my.component';

@NgModule({
  declarations: [
    MyComponent,
  ]
Scrimp answered 28/6, 2020 at 4:39 Comment(0)
C
3

I just imported ClarityModule and it solved all the problems. Give it a try!

import { ClarityModule } from 'clarity-angular';

Also, include the module in the imports.

imports: [ ClarityModule ],

Coreencorel answered 30/3, 2020 at 7:47 Comment(4)
Hey, Ishani. Can you please also add an explanation for why it works?Malacology
If we visit the documentation for CUSTOM_ELEMENTS_SCHEMA, at angular.io/api/core/CUSTOM_ELEMENTS_SCHEMA we will find that CUSTOM_ELEMENTS_SCHEMA allows NgModule to contain non-Angular elements with dash case(-) {similar to this scenario}. Clarity Module when imported includes all the clr-icons, etc by default and we can also use other functionalities of clarity module as well.Coreencorel
This is irrelevant to the problem here. How do you solve it by importing clarity module?? @CoreencorelOceania
if you read the problem statement, Angular is not able to identify clr-header.The same error comes for clr-icon and others. As I mentioned in my previous comment, Clarity module contains these by default. I hope it answered your question.Coreencorel
T
2

Disabling AOT and build-optimizer at least makes it build:

"buildOptimizer": false,
"aot": false,
Timbale answered 24/8, 2021 at 19:16 Comment(0)
R
1

I'd like to add one additional piece of information since the accepted answer above didn't fix my errors completely.

In my scenario, I have a parent component, which holds a child component. And that child component also contains another component.

So, my parent component's spec file need to have the declaration of the child component, AS WELL AS THE CHILD'S CHILD COMPONENT. That finally fixed the issue for me.

Rondarondeau answered 12/10, 2017 at 14:14 Comment(0)
A
1

I think you are using a custom module. You can try the following. You need to add the following to the file your-module.module.ts:

import { GridModule } from '@progress/kendo-angular-grid';
@NgModule({
  declarations: [ ],
  imports: [ CommonModule, GridModule ],
  exports: [ ],
})
Acker answered 20/12, 2019 at 8:16 Comment(0)
D
0

That didn't work for me (using 2.0.0). What worked for me was importing RouterTestingModule instead.

I resolved this by importing RouterTestingModule in spec file.

import {
    RouterTestingModule
} from '@angular/router/testing';

  beforeEach(() => {

        TestBed.configureTestingModule({
            providers: [
                App,
                AppState,
                Renderer,
                {provide: Router,  useClass: MockRouter }
            ],
            imports: [ RouterTestingModule ]
        });

    });
Donahoe answered 13/11, 2017 at 18:22 Comment(0)
Q
0

For me, I needed to look at :

1. If 'cl-header' is an Angular component, then verify that it is part of this module.

This means that your component isn't included in the app.module.ts. Make sure it's imported and then included in the declarations section.

import { NgModule }      from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';

import { UtilModule } from "./modules/util_modules/util.module";
import { RoutingModule } from "./modules/routing_modules/routing.module";

import { HeaderComponent } from "./app/components/header.component";

@NgModule({
    bootstrap: [AppComponent],
    declarations: [
        AppComponent,
        HeaderComponent
    ],
    imports: [BrowserModule, UtilModule, RoutingModule]
})
export class AppModule { }
Quintus answered 21/3, 2018 at 20:50 Comment(0)
A
0

Was having a similar problem, but it turned out there was a misspelling on the component name (selector-name). So Angular was unable to import the module.

Acromegaly answered 13/1, 2022 at 13:25 Comment(0)
W
0

Another reason you might get this error is if you were to load Bootstrap twice. i.e. by first running npm install bootstrap, jquery, popper and then by ALSO adding them by copy and paste from CDN. (Just do one or the other)

Whether answered 26/9, 2022 at 4:40 Comment(0)
M
0

Using the CUSTOM_ELEMENT_SCHEMA will get the code to compile but it's not sorting out the root problem and will create headaches down the line.

I usually get this error when you I'm missing a module import or the custom component isn't defined in a declarations section of the module it's defined in.

Check the imports in your modules, and make sure the custom component is in the declaration section of the module is imported, make sure you import the custom component's module if it's not declared in the app module.

Wanted to down vote and upvoted some of the other responses, the correct answer is between Luis, Vương's responses.

Make sure the component is in the declaration section (custom.module.ts)

import { MyComponent } from './custom/my.component';

@NgModule({
  declarations: [
    MyComponent,
  ]

Make sure the module is imported (app.module.ts or other modules referencing the component):

import { MyCustomModule } from '@custom/custom.module';
@NgModule({
  declarations: [ ],
  imports: [ CommonModule, MyCustomModule ],
  exports: [ ],
})
Mclendon answered 14/6, 2023 at 8:13 Comment(0)
L
0

I suddenly delete component and it throws this error

you can try checking app.module.cs

some imports can have problems from that

Logistics answered 8/1, 2024 at 23:43 Comment(0)
P
-1

Make sure to import component in declarations array

@NgModule({
  declarations: [ExampleComponent],
  imports: [
      CommonModule,
      ExampleRoutingModule,
      ReactiveFormsModule
  ]
})
Pyrenees answered 18/8, 2020 at 8:7 Comment(0)
T
-3

Did you use the webpack... if yes please install

angular2-template-loader

and put it

test: /\.ts$/,
   loaders: ['awesome-typescript-loader', 'angular2-template-loader']
Theurer answered 20/11, 2016 at 14:4 Comment(2)
I cannot path default tests which had been created by the component generating by ng g and got a same error. Nothing from this topic wasn't helpful :( I take off an errors only when I had been commented components spec files :(Slavonic
I understand right that custom tags were working with angular below v2 only?! I have checked something in youtube and I'm trying to test my code from v2 in v4 environmentSlavonic

© 2022 - 2025 — McMap. All rights reserved.