For Angular 4, simply add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of the component in order to permit any element

After using angular-cli to create a new project (ng new my-project-name), I ran npm run test successfully without any issues.

To display font icons in my project, I added the Font Awesome module from https://www.npmjs.com/package/angular-font-awesome.

In my HTML file, I included the

<fa name="bars"></fa>
tag and received the expected output. However, upon running npm run test again, I encountered 3 failures related to the fa tag.

One of the failure reports looked like this:

'fa' is not a known element:
        1. If 'fa' is an Angular component, then verify that it is part of this module.
        2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("--The content below is only a placeholder and can be replaced.-->
        <div style="text-align:center">          [ERROR ->]<fa name="bars"></fa>
          <h1>            Welcome to {{title}}!
        "): ng:///DynamicTestModule/AppComponent.html@2:2        Error: Template parse errors:
            at syntaxError home/harsha/Documents/Projects/testProject/node_modules/@angular/compiler/esm5/compiler.js:466:22)

I attempted solutions like adding NO_ERRORS_SCHEMA and CUSTOM_ELEMENTS_SCHEMA in the app.module.ts file, but none of them resolved the issue.

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

Unfortunately, these fixes did not work as expected.

Answer №1

To properly set up your test spec file, follow this format:

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ yourcomponent ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  }));

Take note of the schemas property within the TestBed.configureTestingModule method. Once you have added the schemas property, your tests should execute smoothly without any errors that might have occurred prior to integrating the Font Awesome component.

Answer №2

To overcome this issue, I implemented a custom component named SampleComponent(sample.ts) in my Ionic project. This component is intended to be used in welcome.html and is part of a common module file called components.module.ts. The structure of the components module is as follows:

import { NgModule,NO_ERRORS_SCHEMA,CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { SampleComponent } from './sample/sample';

@NgModule({
    declarations: [SampleComponent],
    imports: [],
    exports: [SampleComponent],
    schemas: [
        CUSTOM_ELEMENTS_SCHEMA,
        NO_ERRORS_SCHEMA
      ]
})
export class ComponentsModule {}

In welcome.module.ts, where I plan to utilize my sample.component.ts, I included components.module.ts like so:

import { NgModule } from '@angular/core';
import { TranslateModule } from '@ngx-translate/core';
import { IonicPageModule } from 'ionic-angular';

import { WelcomePage } from './welcome';
import { ComponentsModule } from "../../components/components.module";
@NgModule({
  declarations: [
    WelcomePage,
  ],
  imports: [
    IonicPageModule.forChild(WelcomePage),
    TranslateModule.forChild(),
    ComponentsModule
  ],
  exports: [
    WelcomePage
  ]
})
export class WelcomePageModule { }

The content of welcome.html where I have integrated my custom component (SampleComponent)

<ion-content scroll="false">
  <div class="splash-bg"></div>
  <div class="splash-info">
    <div class="splash-logo"></div>
    <div class="splash-intro">
      {{ 'WELCOME_INTRO' | translate }}
    </div>
  </div>
  <div padding>
    <p>`enter code here`
      <sample>loading...</sample>
    </p>
    <button ion-button block (click)="signup()">{{ 'SIGNUP' | translate }}</button>
    <button ion-button block (click)="login()" class="login">{{ 'LOGIN' | translate }}</button>
  </div>
</ion-content>

Answer №3

During the development of my project, I encountered a similar error while implementing a dynamic component approach. The issue was discussed in this thread. In my situation, the error occurred when passing svg tags through the DynamicComponent. To resolve this, I included NO_ERRORS_SCHEMA in the @NgModule of this component:

import { Component, OnChanges, OnInit, Input, NgModule, NgModuleFactory, Compiler, SimpleChanges, NO_ERRORS_SCHEMA } from '@angular/core';
import { SharedModule } from '../../../../../../../../shared.module';

@Component({
    selector: 'dynamic',
    template: `<ng-container *ngComponentOutlet="dynamicComponent; ngModuleFactory: dynamicModule;"></ng-container>`
})

export class DynamicComponent {
    dynamicComponent: any;
    dynamicModule: NgModuleFactory<any>;

    @Input('html') html: string;

    constructor(private compiler: Compiler) {}

    ngOnChanges(changes: SimpleChanges) {
        if (changes['html'] && !changes['html'].isFirstChange()) {
            this.dynamicComponent = this.createNewComponent(this.html);
            this.dynamicModule = this.compiler.compileModuleSync(this.createComponentModule(this.dynamicComponent));
        }
    }

    ngOnInit() {
        this.dynamicComponent = this.createNewComponent(this.html);
        this.dynamicModule = this.compiler.compileModuleSync(this.createComponentModule(this.dynamicComponent));
    }

    protected createComponentModule(componentType: any) {
        @NgModule({
            imports: [SharedModule],
            declarations: [componentType],
            entryComponents: [componentType],
            schemas: [NO_ERRORS_SCHEMA]
        })
        class RuntimeComponentModule {}
        // a module for just this Type
        return RuntimeComponentModule;
    }

    protected createNewComponent(template: string) {

        @Component({
            selector: 'dynamic-component',
            template: template ? template : '<div></div>'
        })
        class MyDynamicComponent {
            //metods passed via dynamic component to svg
            testMe() {
                alert('test passed!');
            }
        }

        return MyDynamicComponent;
    }
}

Answer №4

When dealing with a straightforward scenario where the component is functioning properly but the tests are missing the 'fa' component, it is advisable to refrain from utilizing 'NO_ERRORS_SCHEMA'. Instead, consider incorporating 'AngularFontAwesomeModule' into your TestBed imports.

Answer №5

Just a heads up, when incorporating this NgModule attribute into a feature module, don't forget to include it in your root NgModule as well. At least, that was my experience.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Expose the app's homepage through the nginx server configuration

I currently have a server running Nginx and hosting an Angular 4 application under the domain www.mysite.com. However, I now have another domain called www.mySecondDomain.com and I want this site to open a specific route within the same angular app. For ex ...

Using RxJS with Angular to intercept the valueChanges of a FormControl prior to subscribing

I decided to create a new observable using the values emitted by the FormControls.valueChanges observable. This creation of the observable takes place within the ngOnInit method in the following manner: ngOnInit(): void { this.myObservable$ = combine ...

Angular6 : PrimeNg datatable: the nova-light theme failing to activate

I'm currently working on an Angular 6 app that is equipped with the latest version of PrimeNG (6.1.4) and I am using a simple datatable component. My goal is to apply the nova-light theme to my datatable, but unfortunately, it is not being applied cor ...

Prevent loading data in Angular 5 by handling errors from undefined objects

Is there a way to avoid console errors from undefined objects? Imagine I have the following code: name : string; constructor(private data: DataService) { this.data.name.subscribe(res => this.name = res); } In my HTML, I have this: <p> {{name}} ...

Creating a custom type for accepted arguments in a Typescript method

Below is the structure of a method I have: const a = function (...args: any[]) { console.log(args); } In this function, the type of args is any[]. I am looking to create a specific type for the array of arguments accepted by this method in Typescript. ...

Tips for efficiently handling state across various forms in separate components using only one save button within a React-Redux application

I am currently developing an application that combines a .NET Core backend with a React frontend, using React Hook Form for managing forms. Unlike typical single-page applications, my frontend is not built in such a way. On a specific page of the applicat ...

Typeahead functionality in Angular UI Bootstrap that uses object properties to search and display

I have a similar item (recreation of Map): $scope.vehicles = { 1:{id:1, model:'Coupe'}, 2:{id:2, model:'Truck'}, 3:{id:3, model:'Hatchback'} } I want to utilize the property values in typeahead of ui bootstrap (whil ...

Wrapper functions that are nested are returning a Promise that resolves to another Promise of type T

I have a function called doesPromiseyThings that wraps a thunk and returns its value inside a Promise. I want to create another wrapper that not only handles the creation of thunks, but also ensures the returned type is a Promise-wrapped version of the ori ...

Using Typescript to define Vuex store types

Attempting to create a TypeScript-friendly Vuex store has been quite the challenge. Following instructions outlined here, I've encountered an issue where accessing this.$store from a component results in a type of Store<any>. I'm strugglin ...

How can RootStateOrAny be turned off in React with typescript?

Whenever I need to employ useSelector, I find myself repeating this pattern: const isLoading = useSelector( (state) => state.utils.isLoading ); Is there a shortcut to avoid typing out RootStateOrAny each time? It's starting to become a hassl ...

How to retrieve data from the resolve function in an Angular 2 component

How can I access the resolved data in an Angular 2 migrated component? I have an Angular JS app.config set up with routing that loads the necessary Angular 2 migrated component. .state('users.list', { url: '/users/list', templ ...

Resolve the error message "Class is not a constructor" which arises while utilizing namespaces in TypeScript with WebPack

Issue with TypeScript Namespaces in PIXI.js As I delve into the world of TypeScript and PIXI.js without any framework, I find myself facing a challenge. Previously, at work, we utilized namespaces with the module keyword for a cleaner structure. However, ...

Passing RxJs pipes as a parameter

Is there a way to pass pipes as parameters? For example: var mypipes = [ pipeA(() => { alert("a"); }), pipeB(() => { alert("b"); }) ...

What are the steps to create an object from an array?

Is it possible to create an object from an array in TypeScript? { A: {H: 10, W: 20, S: 30}} using the following data: [ { group: A, name: H, value: 10 }, { group: A, name: W, value: 20}, { group: A, name: S, value: 30} ] L ...

Assessing functionality in Angular8 by testing a function that accesses an array from a service

I have a function that I want to test along with the current test setup: canShowIt() { let showit = false; const profils = this.requestsService.userProfil; showit = profils.some((profil) => profil.id === this.profileDetail.id); return showit; ...

The header remains unchanged even after verifying the user's login status

Currently, I am using Angular 11 for the front-end and Express for the back-end. I am facing an issue with determining if a user is logged in so that I can display the correct header. Even after logging in and setting a cookie in the browser upon redirecti ...

Matching the types of method parameters to the types of callback function parameters in Typescript generics

I am currently working on creating a class that takes a function as a parameter in the constructor. The function can have arguments of any type. My goal is to add a method to the class that also accepts the same arguments as the function parameter, essenti ...

After updating to Angular 9, the ViewChild functionality seems to be malfunctioning

Is there a change in ViewChild behavior? Since upgrading to Angular 9, the MatSideNav menu has ceased to function. export class SidenavOpenCloseExample implements OnInit, AfterViewInit { @ViewChild('menuSide', {read: MatSidenav, static: true} ...

Issues with Angular Material Form Fields Functioning Incorrectly

Recently, I came across a boilerplate template that helped me integrate an Angular Element component into a SharePoint Framework webpart. Following this template and the package.json provided below: "dependencies": { "@angular/animations": "5.2.11", ...

Methods for transforming a TypeScript class instance containing getter/setter properties into a JSON format for storage within a MySQL database

I am currently working on a TypeScript class that includes a getter and setter method: export class KitSection { uid: string; order: number; set layout(layout: KitLayout) { this._layout = new KitLayout(layout); } get layout( ...