如何从主要 Angular 组件设置 html 和 body 的样式?

Sah*_*ndy 4 javascript angular

我正在尝试从主要组件设置 html 和 body 样式:

app.component.styl:

 html, body {
       padding: 0;
       margin: 0;
       background: blue;
    }
Run Code Online (Sandbox Code Playgroud)

似乎它不适用于我的角度组件:

app.component.ts:

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

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.styl']
    })
    export class AppComponent {

    }
Run Code Online (Sandbox Code Playgroud)

app.component.html:

<div class="todo-app">
  <div>
    <input type="text">
    <button>Add</button>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

为什么 html 和 body 选择器不起作用,是否有特殊的角度方法来实现?

Iva*_*S95 6

app.component位于中的index.html的body标签; 像这样

索引.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Angular Alerts</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="assets/img/favicon/favicon.ico">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
  <app-root></app-root> <!-- This is your App Component -->
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

鉴于这种情况,你不能指定bodyhtml使用默认的行为(这意味着如果ViewEncapsulation启用),因为样式作用范围只有组件和组件本身DOES NOT有一个body标签; 您需要在styles.css全局文件中定义样式,或者关闭该组件的 ViewEncapsulation,以便其 css 文件中定义的样式全局应用

  • 你能在 stackblitz 上复制你的问题吗?`styles.css` 是不限定于任何特定组件的全局样式,所以一定有其他事情发生 (2认同)