Creating a DIV element in Angular 5 component rather than using a new tag

Is there a way to instruct Angular to generate a DIV instead of another tag when inserting a component into a router-outlet? Currently, the component code looks like this:

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

@Component({
  selector: 'app-fwc-vpn-main',
  templateUrl: './fwc-vpn-main.component.html',
  styleUrls: ['./fwc-vpn-main.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class FwcVpnMainComponent implements OnInit {

  numbers = new Array(35);

  constructor() { }

  ngOnInit() {
  }

}

What is currently rendered in the final HTML is:

<router-outlet></router-outlet>
<app-fwc-vpn-main class="ng-star-inserted"> ... </app-fwc-vpn-main>

The desired output would be:

<router-outlet></router-outlet>
<div app-fwc-vpn-main class="grid-y medium-grid-frame"> ... </div>

Please note that the grid-y and medium-grid-frame classes need to be added for proper layout. This is why changing the inserted tag to a div is necessary.

Thank you,

Answer №1

When working with Angular, the selector can be declared in one of the following ways:

  • element-name: select by element name.
  • .class: select by class name.
  • [attribute]: select by attribute name.
  • [attribute=value]: select by attribute name and value.
  • :not(sub_selector): select only if the element does not match the sub_selector.
  • selector1, selector2: select if either selector1 or selector2 matches.

During compilation of Angular Component/Directive metadata, the selector is parsed using CssSelector which retains all parsed data such as:

[
  {
    "element": null,
    "classNames": [
      "grid-y",
      "medium-grid-frame"
    ],
    "attrs": [
      "app-fwc-vpn-main",
      ""
    ],
    "notSelectors": []
  }
]

The Angular router dynamically creates components, resulting in each routed component having a Host view. To prepare the template for Host view, the angular compiler generates it based on the metadata extracted from CssSelector:

/** Gets a template string for an element that matches the selector. */
getMatchingElementTemplate(): string {
    const tagName = this.element || 'div';
    const classAttr = this.classNames.length > 0 ? ` class="${this.classNames.join(' ')}"` : '';

    let attrs = '';
    for (let i = 0; i < this.attrs.length; i += 2) {
      const attrName = this.attrs[i];
      const attrValue = this.attrs[i + 1] !== '' ? `="${this.attrs[i + 1]}"` : '';
      attrs += ` ${attrName}${attrValue}`;
   }

   return getHtmlTagDefinition(tagName).isVoid ? `<${tagName}${classAttr}${attrs}/>` :
                                                  `<${tagName}${classAttr}${attrs}></${tagName}>`;
 }

https://github.com/angular/angular/blob/c8a1a14b87e5907458e8e87021e47f9796cb3257/packages/compiler/src/selector.ts#L91-L105

As a result, the host template would look like:

<div class="grid-y medium-grid-frame" app-fwc-vpn-main></div>

Therefore, the provided solution should work effectively:

selector: '[app-fwc-vpn-main].grid-y.medium-grid-frame',

Example

Answer №2

To make the change, modify the selector as follows:

selector: 'app-fwc-vpn-main',

Then update it to:

selector: '[app-fwc-vpn-main]',

Now you can utilize it like this:

<div app-fwc-vpn-main></div>

@Component selector - css selector that identifies this component in a template

You can choose any css selector such as:

.app-fwc-vpn-main // <div class='app-fwc-vpn-main'></div>
#app-fwc-vpn-main // <div id='app-fwc-vpn-main'></div>

For more comprehensive information, refer to: Component

Answer №3

Opt for a directive over a component

<div app-fwc-vpn-main class="grid-y medium-grid-frame"> ... </div>

Here, the app-fwc-vpn-main serves as the directive. By choosing to create a directive instead of a component, you can easily render your desired template.

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

Top method in Angular 6 for verifying if a scrollable section has been scrolled to the very bottom

I am searching for a reliable solution in Angular 6 to determine whether a scrollable host component has reached its maximum scroll bottom. Despite my efforts, I have been unsuccessful in finding a functioning example of a function that can detect if a cu ...

Encountering issue with ngIf directive in Angular

In my Angular project, I am trying to display data from a variable that is formatted in json. I have successfully done this using *ngfor, but now I also want to add a condition where it checks if msg.who=="Bot". My current code looks like this: <div cl ...

Transform object into data transfer object

Looking for the most efficient method to convert a NestJS entity object to a DTO. Assuming the following setup: import { IsString, IsNumber, IsBoolean } from 'class-validator'; import { Exclude } from 'class-transformer'; export clas ...

Navigating an immutable list to make updates to its values

Within this list, I have an unalterable group of objects. My task is to change the value of the 'isReq' property to false for all objects except the one with the id 2. [ { 'id': 1, 'name': 'Ram', 'D ...

Jhipster - displaying the authenticated user on an Angular Frontend

Is there a way to retrieve the ID of the currently logged in user from the frontend of an Angular application generated by Jhipster? I have come across some older solutions using the Principal class, but it appears that method is no longer available. Any ...

What is the appropriate overload to be selected when utilizing a ref in the method call?

Encountering an unfamiliar TS error while working with the code snippet below: <script lang="ts"> import {defineComponent, computed, toRef} from 'vue' import _ from 'lodash' import {DateTime} from 'luxon' int ...

End of container Bootstrap 4 row with two columns at the edge

I'm currently working on an angular project with bootstrap 4. Within the container, there are two rows. I specifically want one row to always be positioned at the bottom of the container. Despite trying methods like justify-content: flex-end;, botto ...

How can I detect when the Redux state object in my Angular (v5) application changes?

Can someone please explain to me the process of creating a listener, like subscribing to the AppState changing? Here is the basic service I currently have. In my view, there is a dispatch action that increments the counter. After the counter changes valu ...

Ways to dynamically generate a generic that expands a union class type

Reviewing the code snippet: const events = { a: ['event1' as const, 'event2' as const], b: ['event3' as const, 'event4' as const], }; class SomeClass< T extends AnotherClass<typeof events[keyof typeof ev ...

The input field in iOS is shielded by the keyboard on Ionic 5

For months now, I've been struggling with the same issue and I just can't seem to find a solution. The problem arises in an application where there are multiple forms; when a user focuses on an input field, the keyboard covers it up completely ma ...

Determine if Toggle Accordion is Expanded by Checking HTML Attribute Using Selenium

I am working with an HTML Angular Material Accordion component. When it is expanded, the class mat-expanded is added. <mat-expansion-panel _ngcontent-ng-cli-universal-c931="" data-qa="product" class="mat-expansion-panel ng- ...

Cypress: Unable to properly stub API with cy.intercept()

Whenever I utilize the cy.intercept() function, the API fails to stub. cy.intercept("GET", `${API}farm/list`, { body: { statusCode: 200, message: "Request successful", result: seededFarmList, }, }); The way I import the fixture file is as ...

Combining nested Observables within an outer array without using inner subscribe (RxJS)

Looking at the TypeScript functions below, which are used for async HTTP-Calls: public retrieveAllMembersIdsFromGroup(groupId: string): Observable<string[]> public retrieveMember(memberId: string): Observable<Member> How can these be combined ...

What types should you use for an Axios response in React and TypeScript?

Trying to display a basic user list fetched from an API, which returns the following data: [{"UserID":2,"FirstName":"User2"},{"UserID":1,"FirstName":"User1"}] Struggling to understand how to deal ...

What steps should be taken to guarantee that the view is created only after receiving values from the route params subscription?

How can I ensure that the View is only rendered after the subscription has received values? When clicking on the Edit button in MyComponent_1, Angular navigates to MyComponent_2. In MyComponent_2, the view contains a form whose values are dependent on rout ...

Error: Null is causing an issue and preventing property 'isSkipSelf' from being read in Angular7

While assembling the package for my module, I encountered the following error. TypeError: Cannot read property 'isSkipSelf' of null at ProviderElementContext._getDependency(C:\Users\ravinder\MyProjectName\node_modules\@ ...

mongoose memory leak attributed to jest

UPDATED 2020-09-14 I've encountered an issue with a test case I wrote. While the testcase passes, it raises a complaint about improper teardown and an open connection. Can anyone help identify the problem: Approach to Solving the Issue - Memory Leak ...

Retrieve the Angular Firebase Document and send it back

I have a question related to retrieving a Document from my FireDatabase. The model I am using is for a user, which looks like this: export class User { useremail: string; userid: string; username: string; constructor(usermail: string, use ...

Showing dynamic icons in Angular 2 applications

My goal is to dynamically load a part of my website, specifically by using icon classes defined in the interface like this: import { OpaqueToken } from "@angular/core"; import {IAppConfig} from './app.interface' export let APP_CONFIG = new Opaq ...

encountering issues while trying to set up an Angular project

I encountered an issue in my Mac's terminal while trying to create a new Angular project. Here is the command I entered in the terminal: ng new ProjectName The error message I received: npm WARN deprecated <a href="/cdn-cgi/l/email-protection ...