Angular2:Render a Component Without Its Wrapping Tag

Angular2 : render a component without its wrapping tag

You can use attribute selectors

@Component({
selector: '[myTd]'
...
})

and then use it like

<td myTd></td>

Angular2+ render a component without any wrapping tag at all

Finally found a working soltion!

My child-component looks like:

@Component({
selector: 'child-component'
templateUrl: './child.template.html'
})
export class ChildComponent {
@ViewChild('childComponentTemplate') childComponentTemplate: TemplateRef<any>;
}

My child template looks like:

<ng-template #childComponentTemplate>
... some content ...
</ng-template>

and my parent template like:

<child-component #wrapper [someInput]="123"></child-component>
<ng-container *ngTemplateOutlet='wrapper.childComponentTemplate'></ng-container>

This way there is no wrapper at all.

Render a Component's content without its tag

I ended up using CSS 'sdisplay: contents. As of Sep 2018, major browsers (except Edge) now (at least partially) supports this. (Ref: caniuse.com)

:host {
display: contents;
}

How to remove extra wrapping elements in the rendered HTML?

Angular components are directives with templates. According to this:

Directive configuration @Directive({ property1: value1, ... })

selector: '.cool-button:not(a)' Specifies a CSS selector that
identifies this directive within a template. Supported selectors
include element, [attribute], .class, and :not().

So component selectors can be also attribute selectors. For your example, instead of writing this:

parent.component.html:

<app-button>
<app-text>
My Text
</app-text>
</app-button>

write this:

parent.component.html:

<button app-button>
<span app-text>My Text</span>
</button>

where :

app-button.component.ts

...  
selector: '[app-button]',
template: `<ng-content></ng-content>
...

app-text.component.ts

...
selector: '[app-text]',
template: `<ng-content></ng-content>`
...

this would be rendered as you expected:

Sample Image

Update after your comment about styling those buttons:

To style the buttons from inside the button component, and set class in parent component, use :host-context pseudo-class. It is not deprecated and works well

button.component.css

  :host-context(.button-1)  {
background: red;
}
:host-context(.button-2) {
background: blue;
}

app.component.html

<button app-button class="button-1">
<span app-text>My Text</span>
</button>

<button app-button class="button-2">
<span app-text>My Text</span>
</button>

Here is the DEMO



Related Topics



Leave a reply



Submit