klauskpm
klauskpm

Reputation: 3125

Is there any way to only render the template/content of my Angular component?

I want to have a clean HTML, only the component content and not the container, because I want to use ITCSS and RSCSS methodologies.

So, thinking that I have 2 components: app-simple-card and app-superior-header; I want have the following structure.

simple-card.component.scss

.simple-card {
    > .header {
        @extends .superior-header;
        @extends .superior-header.-compact;
    }
}

superior-header.component.scss

.superior-header {
    > .title {}

    &.-compact {}
}

The problem

Angular renders a "container" for the component content, forcing me to use the component name as part of the selector. It is against the RSCSS methodology, so I don't want to do it that way, and it would awful to reuse the styles in another project.

Right now, the scss file would look like this:

.simple-card {
    > app-superior-header > .header {...}
}

I also don't want to use the component as an attribute, because it wouldn't solve my problem, and it's not considered a good practice. I need to completely remove/replace the component "container" only showing it's content.

Upvotes: 0

Views: 480

Answers (2)

Lars Gyrup Brink Nielsen
Lars Gyrup Brink Nielsen

Reputation: 4095

I hear what you are saying, but do use an attribute selector for your component and a host binding to add the class to whatever element you are using.

The Angular Style Guide is not a book of laws that you must abide, it simply contains guidelines. If your use case calls for another practice, use it

@Component({
  selector: '[appSimpleCard]',
})
export class SimpleCard {
  @HostBinding('class')
  classList = 'simple-card'; // or rather 'c-simple-card'
}

Using attribute selector for component like it was a regular directive, you can control all attributes including adding the ITCSS Component Class and events for the host element with host bindings and host listeners as well as render a template. This is exactly what we want.

As another benefit, you won't have to add :host { display: block } to the component styles as is normally the case with all custom element tags. You also save an additional element in the DOM for each component rendered in this way which can add up to quite a few saved elements in a complex app.

This will not work with native view encapsulation (shadow DOM).

Upvotes: -1

Jonas
Jonas

Reputation: 47

Within the component styling, you can target the component element with

:host {}

If you want to target children within a component use

&/deep/ {}

Upvotes: -1

Related Questions