角度2:造型路由器出口宽度<100%

Koe*_*uck 8 css angular2-template angular

我正在构建一个Angular 2应用程序,它有一个侧导航栏,用于宽度超过500的屏幕,以及一个底部导航栏,用于宽度小于500的屏幕.现在我试图为侧栏指定20%的宽度,80 %到应用内容.

我遇到的问题是路由器插座内容(即实际的应用程序)占用了页面的整个宽度而不是80%.它似乎忽略了我试图给它的任何造型.我们不应该直接设置路由器插座的样式吗?或者也许有一种更好的方式让我俯瞰?

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*ota 21

简单的解决方案就是放入<router-outlet>一个样式div:

<div style="width:80%;float:right;">
    <router-outlet></router-outlet>
</div>
Run Code Online (Sandbox Code Playgroud)


moh*_*rim 11

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

:host(selector) { width:70% }
Run Code Online (Sandbox Code Playgroud)

以下是组件:

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%
Run Code Online (Sandbox Code Playgroud)


Val*_*Val 5

关键是/ deep /关键字:

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

由于该组件是在标记之后动态加载的,因此选择器“ +”会匹配其旁边的所有内容。

:not()选择器不包含模板中的元素。

编辑2018/3/1:

由于角4.3.0/deep/过时了,它的建议选择是::ng-deep。对此进行了长时间的讨论

  • / deep /已弃用。 (3认同)
  • 使用:: ng-deep代替/ deep / (3认同)