What to use in place of ::ng-deep

后端 未结 7 784
梦毁少年i
梦毁少年i 2020-11-22 10:42

I\'m trying to style an element placed by the router outlet in angular and want to make sure that the element generated gets a width of 100%

From most of the replies

相关标签:
7条回答
  • 2020-11-22 11:29

    To avoid changing the default encapsulation, I wrote a helper that append global styles for the component:

    deepStyle.ts

    import { ViewContainerRef } from '@angular/core';
    
    export function deepStyle(vcr: ViewContainerRef, csss: string[]){
        let id = 'deep-' + vcr.element.nativeElement.tagName;
        let styleElement = document.getElementById('pierce-' + vcr.element.nativeElement.name);
        if(!styleElement){
            styleElement = document.createElement('style');
            styleElement.id = id;
            styleElement.innerHTML = csss.map(css => vcr.element.nativeElement.tagName + ' ' + css).join('\n');
            document.head.append(styleElement);
        }
    }
    

    my-component.ts

    import { Component, ViewContainerRef } from '@angular/core';
    import { deepStyle } from '../deepStyle';
    
    @Component({
      selector: 'my-component',
      templateUrl: './my-component.html',
      styleUrls: ['./my-component.css']
    })
    export class MyComponent {
       constructor(vcr: ViewContainerRef) {
        deepStyle(vcr, [`
           img {
             height: 180px;
           }
        `]);
      }
    }
    

    result:

    <head>
    ...
    <style id="deep-MY-COMPONENT">
        MY-COMPONENT img {
          height: 180px;
        }
    </style>
    ...
    </head>
    
    0 讨论(0)
提交回复
热议问题