Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style html and body from the main Angular component?

I am trying to style html and body from the main component:

app.component.styl:

 html, body {
       padding: 0;
       margin: 0;
       background: blue;
    }

and seems it does not work with my angular component:

app.component.ts:

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

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

    }

app.component.html:

<div class="todo-app">
  <div>
    <input type="text">
    <button>Add</button>
  </div>
</div>

Why html and body selector don't work, is there a special angular method to achieve that??

like image 629
Saher Elgendy Avatar asked Jan 02 '23 12:01

Saher Elgendy


2 Answers

The app.component is located inside the index.html's body tag; like this

index.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>

Given that, you can't target body or html with the default behavior (that means if ViewEncapsulation is enabled), since styles are scoped to that component only, and the component itself DOES NOT have a body tag; you need to define the styles in the styles.css global file, or turn ViewEncapsulation off for that component so the styles defined in its css file apply globally

like image 140
IvanS95 Avatar answered Jan 04 '23 04:01

IvanS95


If you need that the style is apply to all project, you need to deactivate Encapsulation in css,

@Component({
   ...
   encapsulation: ViewEncapsulation.None
   ...
})

Here a nice article about that. But I recommend you set the style in style.css or style.scss in the root of your project.

like image 26
Carlos Osiel Avatar answered Jan 04 '23 05:01

Carlos Osiel