Angular component name constraints - 'the selector [your component name] is not permissible'

When trying to generate a component using the Angular 6 CLI (version 6.0.7), I encountered an issue. After typing in ng g c t1-2-3-user, I received an error message stating that the selector (app-t1-2-3-user) is invalid.

I wondered if there was something inherent about this name that was not allowed by Angular. Interestingly, I had previously created a parent module named t1-myModule using ng g module t1-myModule without any issues. The problem seems to be specific to naming a component as t1-2-3-user within that module.

To test this hypothesis, I tried creating a different component with the command ng g c t1-testComponent and it worked perfectly. So, it appears that the CLI is functioning properly, but there may be some restriction on naming conventions for components like t1-2-3-user in Angular.

EDIT: Upon further investigation, I discovered that Angular dislikes having a number as the first character after a dash (-) in a component name. This limitation might be similar to restrictions found in JavaScript variables, considering that Angular eventually compiles into JavaScript. Can anyone provide more insight or confirm this constraint on component naming?

Answer №1

According to the regulations set by W3C standards, selectors must meet the following criteria:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain

  1. only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_);
  2. they cannot start with a digit, two hyphens, or a hyphen followed by a digit
  3. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".

Angular adheres to this W3C convention for selector names. A similar validation process is performed within the Angular CLI codebase. The actual implementation involves using a regular expression (

/^[a-zA-Z][.0-9a-zA-Z]*(:?-[a-zA-Z][.0-9a-zA-Z]*)*$/
) to ensure that the specified selector meets the required criteria before creating files.

When executing the

ng generate component component-name
command, Angular calls upon @angular/schematics for the component command and supplies the component name as a parameter. This triggers a validation check on the selector, as demonstrated in the following line of code: below line.

validateHtmlSelector(options.selector);

For further details, refer to validation.ts

export const htmlSelectorRe = /^[a-zA-Z][.0-9a-zA-Z]*(:?-[a-zA-Z][.0-9a-zA-Z]*)*$/;
export function validateHtmlSelector(selector: string): void {
  if (selector && !htmlSelectorRe.test(selector)) {
    throw new SchematicsException(tags.oneLine`Selector (${selector})
        is invalid.`);
  }
}

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

Displaying a div component in React and Typescript upon clicking an element

I've been working on a to-do list project using React and TypeScript. In order to display my completed tasks, I have added a "done" button to the DOM that triggers a function when clicked. Initially, I attempted to use a useState hook in the function ...

What steps should we take to ensure that the container beside the fixed left navigation bar is responsive?

Currently, I am working on creating a user interface that features a fixed navigation bar on the left hand side and a responsive content window. Here is what I have implemented so far: <div style="width: 15%; float: left; display: inline;"> <na ...

Making an Angular POST request and then navigating to a new component

Hello, I am a beginner in Angular and struggling to make my code work. It seems like a basic functionality issue that I can't seem to figure out. My goal is to send a post request to my .NET core API to register a user, and once that is done, navigat ...

Angular library generation causing circular dependencies

Modification Required It has come to my attention that the issue of a circular dependency arises solely when utilizing a production build - ng build lib --prod My task involves creating an Angular library intended for utilization in a separate Angular pr ...

Implementing Azure AD authentication with Angular and .NET Core 2 Web API

My goal is to implement authentication in my application using Azure AD Currently, the flow of my application looks like this: User -> AngularApp -> Azure Login -> AngularApp with token -> API Call to backend with token -> Backend verifies token with Azu ...

@ngrx effects ensure switchmap does not stop on error

Throughout the sign up process, I make 3 http calls: signing up with an auth provider, creating an account within the API, and then logging in. If the signup with the auth provider fails (e.g. due to an existing account), the process still tries to create ...

What is the best way to store a small number of files in the state

I have recently implemented Drag and Drop functionality, and now I am facing an issue where I need to save a few files in state. const [uploadedFiles, setUploadedFiles] = useState<any[]>([]); const onDropHandler = async (e: React.DragEvent<HTMLDi ...

How to efficiently retrieve automatically generated elements by ID in Angular 2

In order to create a 6x6 grid, I am using the following code: <ion-grid> <ion-row *ngFor="let rowIndex of createRange(6)" [attr.id]="'row-'+rowIndex"> <ion-col col-2 *ngFor="let colIndex of createRange(6)" [attr.id]= ...

When accessing a method exposed in Angular2 from an external application, the binding changes are lost

In my code, I have a method that is made public and accessible through the window object. This method interacts with a Component and updates a variable in the template. However, even after changing the value of the variable, the *ngIf() directive does not ...

Issue C2039: 'IsNearDeath' cannot be found within 'Nan::Persistent<v8::Object,v8 ::NonCopyablePersistentTraits<T>>'

After updating my nodejs to v12.3.1, I encountered errors when attempting to execute npm install in my project directory. error C2059: syntax error: ')' (compiling source file ..\src\custo m_importer_bridge.cpp) error C2660: 'v8 ...

Adjust the size of the mat-expansion indicator to your desired height and width

Trying to modify the width and height of the mat indicator has been a bit challenging. Despite following suggestions from other similar questions, such as adjusting the border width and padding, I am still unable to see the changes reflect in my CSS file ...

Building an advanced numerical input validation system with Angular 7

In AngularJS, the following code is used to create a form with an input field of type "number": <form name="f" novalidate> <input type="number" ng-model="x" name="x"> </form> <div ng-if="f.x.$error.number">NaN</div> Is it p ...

Resolving Node.js Absolute Module Paths with TypeScript

Currently, I am facing an issue where the modules need to be resolved based on the baseUrl so that the output code is compatible with node.js. Here is my file path: src/server/index.ts import express = require('express'); import {port, database ...

When using the RxJs Pipe with MAP in Angular and Ionic, it may not return a value in windows, but it works perfectly in Mac when used with HttpClient

I'm currently using RxJs Pipe with Map for a network request in my Angular/Ionic project. Interestingly, while I do receive a successful response in the network log, the MAP function fails to return any value. Notable Observations Strangely, this fu ...

Enhancing MUI themes by incorporating module augmentation for multiple typings

I am looking to create a repository with two directories, each using MUI and TypeScript. Both directories will have their own theme defined in one ThemeProvider per root. In the main index.tsx file in the root directory, I want to specify which component t ...

Customize the MUISelect style within a universal theme

I need to override a specific style for numerous components, but it is currently only working for all components except the Select. Here is what I am attempting: MuiSelect: { styleOverrides: { select: { ...

Using TypeScript TSX with type parameters

Is it possible to define type parameters in TypeScript TSX syntax? For instance, if I have a class Table<T>, can I use something like <Table<Person> data={...} /> ...

Changing the Value of an Input Element Dynamically in React: A Step-by-Step Guide

In a scenario where I have a component that takes an element, such as <input />, and I need to update its value programmatically after 15 seconds. Initially, I had the following approach in mind: const MyComponent = (myInput: JSX.Element) => { ...

Using mat-select along with formControl to establish the default value

I'm struggling to assign a default value to my formControl, but it doesn't seem to be working as expected. select-hint-error-example.ts export class SelectHintErrorExample { animalControl = new FormControl('', [Validators.required]) ...

Retrieve an enumeration from a value within an enumeration

In my coding project, I have an enum called Animals and I've been working on a function that should return the value as an enum if it is valid. enum Animals { WOLF = 'wolf', BADGER = 'badger', CAT = 'cat', } cons ...