78
votes

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)?

2
Just FYI, this has been asked at least 3 times already: 1, 2, 3.Mark Rajcok
The duplicates simply highlight the various scenarios this feature is required in. As this question points out, the CSS libraries don't work as expected with Angular because of this.Karma

2 Answers

66
votes

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.

11
votes

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 ;-)