Remove/replace a component's selector tag from HTML

Angular

Angular Problem Overview


I am getting started with the Angular 2 (version 2.0.0-alpha.46) and creating a few components.

When creating the component with the below code:

Typescript:

import {ComponentMetadata as Component, ViewMetadata as View} from 'angular2/angular2';

@Component({
   selector: 'my-component'
})

@View({
     template: '<div class="myClass">Hello My component</div>'
 })

export class MyCompoent{
    constructor() {
	    console.info('My Component Mounted Successfully');
    }
}

HTML:

<my-component></my-component>

It works fine, but when i do Inspect element, I can see a tag generated like this:

Output HTML

<my-component>
    <div>Hello My component</div>
<my-component>

Problem

it keeps the <my-component> tag in the HTML, and some of my CSS are not working as expected.

Question

Is there a way to remove the <my-component> tag similar to angular 1 (replace: true in the directive)?

Angular Solutions


Solution 1 - Angular

Replace was deprecated in AngularJS 1.x according to https://github.com/angular/angular/issues/3866 because it seemed to not be a good idea.

As a workaround you can use an attribute selector in your component like

selector: '[my-component]'

selector: '[myComponent]'

and then use it like

<div my-component>Hello My component</div>

<div myComponent>Hello My component</div>

hint

Directive selectors should be camelCase instead of snake-case. Snake-case is only used for element selectors, because the - is required for custom elements. Angular doesn't depend on components being custom elements, but it's considered good practice to comply with this rule anyway. Angular works fine with camelCase attributes and uses them with all directives (*ngFor, ngModel, ...), and is also suggested by the Angular style guide.

Solution 2 - Angular

To quote the Angular 1 to Angular 2 Upgrade Strategy doc:

> Directives that replace their host element (replace: true directives in Angular 1) are not supported in Angular 2. In many cases these directives can be upgraded over to regular component directives.

In fact, it depends on what you want to do and you need to be aware that Angular2 supports several things:

According to what you want to do, you can choose different approaches. For your simple sample, it seems that the @Günter solution is the better ;-)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionpowercoder23View Question on Stackoverflow
Solution 1 - AngularGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - AngularThierry TemplierView Answer on Stackoverflow