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

Tips for adjusting the zIndex of the temporary drawer component in TypeScript

Currently, I am working on incorporating a "temporary" drawer that is clipped under the app bar. Please note that the drawer variant is set to 'temporary' and it needs to be clipped under the app bar. If you need more information, refer to my pr ...

What is the most effective way to use a withLatestFrom within an effect when integrating a selector with props (MemoizedSelectorWithProps) sourced from the action?

I am struggling to utilize a selector with props (of type MemoizedSelectorWithProps) in an effect inside WithLatestFrom. The issue arises because the parameter for the selector (the props) is derived from the action payload, making it difficult for withLat ...

Containerizing Next.js with TypeScript

Attempting to create a Docker Image of my Nextjs frontend (React) application for production, but encountering issues with TypeScript integration. Here is the Dockerfile: FROM node:14-alpine3.14 as deps RUN apk add --no-cache tini ENTRYPOINT ["/sbin ...

Encountering the "UnauthorizedError: jwt malformed" issue when using Auth0Lock for authentication in an express and angular2 application

TL;DR: Upon logging in, the JWT saved on the client-side is sent to the server using angular2-jwt and verified with express-jwt, resulting in an "UnauthorizedError: jwt malformed" message. Greetings! I'm currently developing a Single Page Application ...

Refresh the information being received without initiating a new process

I am fetching data from an ngrx/store I have subscribed to the data this.store.select(somedataList) .subscribe(myList => { myList.propertyA = "a different value"; }); After modifying the property values upon subscription, I must update the data ...

I find myself hindered by TypeScript when trying to specify the accurate constraints for getUserMedia

I'm having difficulty getting a screen to stream within my Angular 5 Electron application. I am utilizing the desktopCapturer feature provided by Electron. Below is an excerpt of my code: loadCurrentScreensource() { desktopCapturer.getSources({ ...

Exploring Angular 4: Iterating Over Observables to Fetch Data into a Fresh Array

Context Currently, I am in the process of developing a find feature for a chat application. In this setup, each set of messages is identified by an index. The goal of the `find()` function is to retrieve each message collection reference from the `message ...

Can a single shield protect every part of an Angular application?

I have configured my application in a way where most components are protected, but the main page "/" is still accessible to users. I am looking for a solution that would automatically redirect unauthenticated users to "/login" without having to make every ...

Combine an array of objects that are dynamically created into a single object

Having trouble transforming the JSON below into the desired JSON format using JavaScript. Current JSON: { "furniture": { "matter": [ { "matter1": "Matter 1 value" }, { "matter2": "Matter 2 value" }, { ...

What is the best way to ensure that Interface (or type) Properties always begin with a particular character?

I attempted to tackle this assignment using template literals, but unfortunately, I wasn't successful. Here is the interface that I am working with: interface SomeInterface { '@prop1': string; '@prop2': string; '@ ...

What is the reason for the continual appearance of the *ngIf validation message?

Currently, I am working with Angular and HTML. I have implemented pattern validation for the first name field, which should not accept only numbers. <fieldset class="six"> <input id="firstName" ng-pattern="^[a-zA-Z]+$" type="text" ...

Struggling to make Typescript recognize the css prop (emotion) when styling Material-UI components

I'm on a mission to set up a Typescript project with Material-UI v4.11.4 and implement emotion for styling in anticipation of the MUI v5 release. The aim is to integrate emotion into the project so developers can transition to using the new styling in ...

Modify the innerHTML to adjust font size when a button is clicked in Ionic 5, or eliminate any unnecessary spaces

I have been experimenting with changing the font size of a variable in .html when the variable contains whitespace. In my .ts page, I use the following code to remove the whitespace: this.contents = this.sanitizer.bypassSecurityTrustHtml(this.product[&apos ...

Conceal multiple parameters within routing for added security

I have setup my Angular component with a button that triggers an event. Inside this event, I currently have: this.router.navigate('page2') While I am aware that query parameters can be passed inside the URL, I am faced with the challenge of pas ...

"Every time you run mat sort, it works flawlessly once before encountering an

I am having an issue with a dynamic mat table that includes sorting functionality. dataSource: MatTableDataSource<MemberList>; @Output() walkthroughData: EventEmitter<number> = new EventEmitter(); @ViewChild(MatSort, { static: true }) sort ...

What is the best way to prevent updating the state before the selection of the end date in a date range using react-datepicker?

Managing user input values in my application to render a chart has been a bit tricky. Users select a start date, an end date, and another parameter to generate the chart. The issue arises when users need to edit the dates using react-datepicker. When the s ...

Generate a TemplateRef and place it into the template of the component

Inquiring about Angular 5.0.2 After reviewing the example provided on NgTemplateOutlet at https://angular.io/api/common/NgTemplateOutlet I am eager to discover if there is a method to dynamically generate a TemplateRef and then insert it into the componen ...

Why aren't my arrays' characteristics being recognized when I create an instance of this class?

There is a puzzling issue with the arrays in my class. Despite creating them, when I try to access them in another class they are not recognized, only the otherProp is visible. To make matters worse, attempting to add elements to the arrays results in an ...

Displaying exclusively the country code in an Angular material-select component

This is the HTML code I am using: <mat-form-field style="width: 70px;margin-left: 50px;"> <mat-label>Select an option</mat-label> <mat-select (openedChange)="toogleCountry()" [(value)]="selected"> <mat-option value="+91" ...

Error in TypeScript while running the command "tsd install jquery" - the identifier "document" could not be found

Currently, I am facing an issue with importing jQuery into my TypeScript project. In order to achieve this, I executed the command tsd install jquery --save, which generated a jquery.d.ts file and added /// <reference path="jquery/jquery.d.ts" /> to ...