Angular 2:设计路由器出口的宽度 < 100%

Angular 2: Styling router-outlet to have width < 100%

我正在构建一个 Angular 2 应用程序,该应用程序将有一个用于宽度超过 500 的屏幕的侧导航栏,以及一个用于宽度小于 500 的屏幕的底部导航栏。现在我正在尝试分配一个侧边栏宽度为 20%,应用内容宽度为 80%。

我遇到的问题是路由器出口内容(即实际应用程序)占据了页面的整个宽度,而不是仅仅 80%。它似乎忽略了我尝试赋予它的任何样式。我们不应该直接设计 router-outlet 样式吗?或者我忽略了更好的方法?

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);
  }
}

简单的解决方案是将 <router-outlet> 放入样式化的 div:

<div style="width:80%;float:right;">
    <router-outlet></router-outlet>
</div>

关键是/deep/关键字:

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

由于组件是在标记之后动态加载的,选择器“+”匹配它旁边的任何内容。

并且 :not() 选择器排除了模板中的元素。

2018/3/1 编辑:

因为 Angular 4.3.0 made /deep/ deprecated, its suggested alternative is ::ng-deep. And there were a long discussion 关于这个。

通过使用:host我们可以在加载组件的同时修改样式。

:host(selector) { width:70% }

组件如下:

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%

您可以对 css 网格执行相同的操作。作为接受答案的宽度,它似乎只在周围 div

在组件文件的@Component({})中使用host:{'style':'width:70%'}设置child的宽度