简体   繁体   中英

Angular 8 render component without extra wrapper element in the DOM

I am trying to split my presentational component to multiple components. When I use selector like this:

@Component({
  selector: 'app-video',
  templateUrl: './video.component.html',
  styleUrls: ['./video.component.scss']
})

it adds a wrapper "app-video" element as a parent of my component and it breaks my styling. Because I expect to have DOM structure like this:

<div class="container">
   <div>myComponentContent</div>
</div>

and instead I get this:

<div class="container">
   <app-video>
     <div>myComponentContent</div>
   </app-video>
</div>

I don't need this wrapper element. Because I expect that my component must be the direct child of my container.

one way that solves this problem is that I use either a class selector or the selector like this:

@Component({
  selector: '[app-video]',
  templateUrl: './video.component.html',
  styleUrls: ['./video.component.scss']
})

Which works fine, but tslint complains about it because it is considered as a bad practice according to angular style guides:

https://angular.io/guide/styleguide#style-05-03

Can anyone tell me the best and valid way to achieve this?

It is better to follow best practices. So try to add style into global style to keep your selector selector: 'app-video' :

div app-video {
    background: lightorange;
}

UPDATE:

As an alternative, you can try to remove selectors something like this:

constructor(private el: ElementRef) {
}


ngOnInit() {
    let yourNativeElement: HTMLElement = this.el.nativeElement,
        parentElement: HTMLElement = nativeElement.parentElement;
    // get all children and move them out of the element
    while (nativeElement.firstChild) {
        parentElement.insertBefore(nativeElement.firstChild, nativeElement);
    }
    // remove the empty element(the host)
    parentElement.removeChild(nativeElement);
}

也许您应该考虑使用视图封装:无,在您的组件上https://angular.io/api/core/ViewEncapsulation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM