Angular6 hiding component selector

It's sometimes useful to have angular's component selector not to be rendered in the page, as sometimes this can cause problems with CSS rendering (since we will have an intermediate tag in between 2 tags)

For example :


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

@Input()
title:String;


}
...

Now you will use your component for example like so :


<html>
.....

<div class='container'>
<my-component [title]="'Test'" ></my-component>

</div>
.....

</html>

With this approach in the rendered HTML you will have the angular component tab generated inside the div but what if this causes problems with some CSS code ?

Well luckily enough there's a simple way to change this and that is changer your selector from a tag to an attribute


@Component({
    selector: '[my-component]'
})
export class MyComponent{

@Input()
title:String;


}
...

By changing the value of the selector property from my-component to [my-component] you should be able to "apply" your component directly to a standard HTML tag, so this will prevent the <my-component> tag to be rendered in the final HTML


<html>
.....
<div class='container' [title]="'Test'" my-component >


</div>
.....

</html>

No comments:

Post a Comment