Search code examples
angularscrolltailwind-cssencapsulation

How do i remove the wrapper element added by Angular to a component?


I am making an Angular app + Tailwind that is one large horizontal page that allows the user to scroll from left to right using scroll-snap-type. When i try to cleanup my code and create reusable components the rendered html is different than when i have all my HTML in one component.

I have created a ScrollContainerComponent:

import { ChangeDetectionStrategy, Component, ElementRef, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-scroll-container',
  standalone: true,
  template: `
    <div
      class="flex snap-x snap-proximity h-screen w-full mx:auto overflow-x-scroll overflow-y-hidden "
      #scrollContainer
    >
      <ng-content></ng-content>
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ScrollContainerComponent {
  @ViewChild('scrollContainer')
  scrollContainer!: ElementRef;

  ngAfterViewInit() {
    this.scrollContainer.nativeElement.addEventListener('keydown', this.handleKeydown.bind(this));
  }

  handleKeydown(event: KeyboardEvent) {
    switch (event.key) {
      case 'ArrowLeft':
        this.scrollLeft();
        break;
      case 'ArrowRight':
        this.scrollRight();
        break;
    }
  }

  scrollLeft() {
    this.scrollContainer.nativeElement.scrollLeft -= 100;
  }

  scrollRight() {
    this.scrollContainer.nativeElement.scrollLeft += 100;
  }
}

And a child:

import { ChangeDetectionStrategy, Component } from '@angular/core';

@Component({
  selector: 'app-scroll-child',
  template: `<div class="snap-start shrink-0 grid w-full h-screen place-items-center text-8xl">
    <ng-content></ng-content>
  </div>`,
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
})
export class ScrollChildComponent {}

However the it only works when i use it like this:

<app-scroll-container>
      <div class="snap-start shrink-0 bg-amber-200 grid w-full h-screen place-items-center  text-8xl">1</div>
      <div class="snap-start shrink-0 bg-blue-200 grid w-screen h-screen place-items-center text-8xl">2</div>
      <div class="snap-start shrink-0 bg-orange-200 grid w-screen h-screen place-items-center text-8xl">3</div>
      <div class="snap-start shrink-0 bg-green-200 grid w-screen h-screen place-items-center text-8xl">4</div>
    </app-scroll-container>

Instead of using the <app-scroll-child>1</app-scroll-child>.

Please help me in removing the wrapper element angular adds to app-scroll-child


Solution

  • If your selector it's in the way, see the [ ]

    selector: '[app-scroll-child]'
    

    You can applied to any html tag, e.g. a div

    <div app-scroll-child 
          class="snap-start shrink-0 grid w-full h-screen place-items-center text-8xl">
    
          <div class="snap-start shrink-0 bg-amber-200...</div>
          ...
    </div>