Angular 2: Styling router-outlet to have width <

2019-06-19 12:30发布

I'm building an Angular 2 app which would have a side nav bar for screens wider than 500, and a bottom nav bar for screens less wide than 500. For now I was trying to assign a 20% width to the side bar, 80% to app content.

The problem that I have is that the router-outlet content (i.e. the actual app) takes up the full width of the page instead of just 80%. It seems to be ignoring any styling I try to give it. Are we not supposed to style router-outlet directly? Or perhaps there is a better way that I'm overlooking?

app.component.ts

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

@Component({
  selector: 'my-app',
  template: `
    <div class="container-fluid">
      <nav *ngIf="this.window.innerWidth > 500"></nav>
      <router-outlet style="width:80%;float:right;"></router-outlet>
      <nav *ngIf="this.window.innerWidth < 500"></nav>
  `,
  styleUrls: ['app/app.component.css']
})
export class AppComponent {
  window = [];

  ngOnInit(): void {
    this.window.innerWidth = window.innerWidth;
  }

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.window.innerWidth = event.target.innerWidth;
    console.log(this.window.innerWidth);
  }
}

4条回答
混吃等死
2楼-- · 2019-06-19 12:32

you could do the same with css grid. as width the accepted answer, it seems to only work in a surrounding div

查看更多
做个烂人
3楼-- · 2019-06-19 12:34

By using :host we can modify the style while loading the component.

:host(selector) { width:70% }

Following is the component:

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

@Component({
  selector: 'test-selector',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent{
}

//test.component.css content
:host(test-selector) { width:70% } will reduce the width to 70%
查看更多
走好不送
4楼-- · 2019-06-19 12:48

Simple solution is to just put <router-outlet> in a styled div:

<div style="width:80%;float:right;">
    <router-outlet></router-outlet>
</div>
查看更多
欢心
5楼-- · 2019-06-19 12:58

The key is /deep/ keyword:

:host /deep/ router-outlet + *:not(nav) {
   width:80%;
   float:right;
}

Since the component is dynamically loaded right after tag, the selector '+' matches anything next to it.

And the :not() selector excludes element in your template.

Edited 2018/3/1:

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

查看更多
登录 后发表回答