1

I have an ngFor loop in one of my Angular templates that includes another component, here's a snippet:

<div *ngFor="let thing of things" (click)="onClick($event, thing)"> <app-thing [data]="thing"></app-thing> </div> 

and Angular is wrapping each app-thing with a div containing an attribute called _ngcontent_c4 as follows:

<div _ngcontent_c4> <app-thing...> <!-- ... --> </app-thing> </div> <div _ngcontent_c4> <app-thing...> <!-- ... --> </app-thing> </div> <div _ngcontent_c4> <app-thing...> <!-- ... --> </app-thing> </div> <!-- ... ---> 

The parent div wrapper is causing issues, especially with styling, and making it harder to use the :host selector to style the component itself. I had to move some styling outside the :host to target the parent to get my flexbox layout working properly.

Is there a way to get Angular not to wrap components?

2 Answers 2

3

Instead of iterating the components within a div, rather iterate the component itself, this will apply (this) styles.

<div *ngFor="let thing of things" (click)="onClick($event, thing)"> <app-thing [data]="thing"></app-thing> </div> 

Rather do this:

<app-thing *ngFor="let thing of things" (click)="onClick($event, thing)" [data]="thing"></app-thing> 

This will make styling easier, and will keep your styles within its component, like you intended it to.

Sign up to request clarification or add additional context in comments.

Comments

3

You can control how Angular applies styles to your components by seting encapsulation property in component metadata:

@Component({ encapsulation: ViewEncapsulation.None, }) export class Component {} 

ViewEncapsulation.None will not add extra attributes. Check ViewEncapsulation and Component Styles in docs for more info.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.