Remove / replace component selector tag from HTML

I start with Angular 2 (version 2.0.0-alpha.46) and create some components.

When creating a component with the code below:

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 the Inspect element , I see a tag generated like this:

HTML output

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

problem

it saves <my-component> in HTML and some of my CSS are not working properly.

Question

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

+71
javascript angular
Jan 04 '16 at 10:20
source share
2 answers

Replacing was forbidden in AngularJS 1.x according to https://github.com/angular/angular/issues/3866, because it seemed like this was not a good idea.

As a workaround, you can use the attribute selector in your component as

 selector: '[my-component]' 

 selector: '[myComponent]' 

and then use it as

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

 <div myComponent>Hello My component</div> 

hint

Directory selectors should be camelCase instead of a snake case. Snake-case is used only for element selectors, because - required for custom elements. Angular does not depend on whether the components are user-defined elements, but it is recommended that this rule be respected anyway. Angular works great with camelCase attributes and uses them with all directives ( *ngFor , ngModel , ...), and is also offered in the Angular style guide.

+65
Jan 04 '16 at 10:25
source share

To quote the documentation from Upgrade 1 to Angular 2 :

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

Actually, it depends on what you want to do, and you should know that Angular2 supports several things:

Depending on what you want to do, you can choose different approaches. For your simple example, it seems that @ Günter's solution is better ;-)

+11
Jan 04 '16 at 10:43
source share



All Articles