Angular 2:样式化router-outlet为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>

通过使用: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%

关键字是/deep/keyword:

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

由于组件是在标签后动态加载的,所以选择器'+'会匹配它旁边的任何内容。

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

编辑2018/3/1:

由于Angular 4.3.0弃用了/deep/,它的替代方案是::ng-deep。我们对此进行了很长时间的讨论。

在组件文件的@Component({})中使用host:{'style':'width:70%'}来设置子元素

的宽度

你可以对CSS网格做同样的事情。宽度是公认的答案,它似乎只适用于周围的div

最新更新