How to apply css class to a component element when it's created by router-outlet?

前端 未结 11 1436
南旧
南旧 2020-12-15 15:41

I have DOM that looks something like this:


    
    ...



        
相关标签:
11条回答
  • 2020-12-15 15:43

    You can use the adjacent sibling selector

    router-outlet + project { ... }
    

    https://developer.mozilla.org/en/docs/Web/CSS/Adjacent_sibling_selectors

    but only if @drewmoore's approach doesn't apply.

    0 讨论(0)
  • 2020-12-15 15:50
    <app>
      <div class="your css class">
       <router-outlet></router-outlet>
    </div>
    </app>
    

    This works for me

    0 讨论(0)
  • 2020-12-15 15:52

    since router injects the component after the the router-outler element, if we would like to style all injected component with the same set of rules the folowing rule is can be helpful.

    the css "+" operator select the first sibling element of a certain type, while asterisk (*) is used as a wild card to select any 1st sibling of router-outlet

    router-outlet + * {
      // your rules
    }
    
    0 讨论(0)
  • 2020-12-15 15:56

    The key is /deep/ keyword:

        :host /deep/ router-outlet + project {
            display: block;
            border: 10px solid black;
        }
    

    This works without any extra configurations.

    :host /deep/ router-outlet + * for whatever component dynamically created by Angular Router.

    Edited 2018/3/5:

    Since Angular 4.3.0 made /deep/ deprecated, its suggested alternative is ::ng-deep. And there were a long discussion about this.

    0 讨论(0)
  • 2020-12-15 15:58

    If you need to add a class conditionally, you can add it programmatically from the component:

    constructor(private renderer: Renderer2, private elemRef: ElementRef) {
      if(someCondition){
        renderer.addClass(elemRef.nativeElement, 'myClass');
      }
    }
    
    0 讨论(0)
  • 2020-12-15 16:00

    use the adjacent sibling selector and the * wildcard to select the element immediately following the router-outlet


    styles.css

    router-outlet + * {
      /* your css */
    }
    

    0 讨论(0)
提交回复
热议问题