Table of Contents
How component styles work
Explore
App Component
App component
Blue button component
Summary
:host, :host-context, ::ng-deep
:host
:host-context
::ng-deep
总结
Home Web Front-end JS Tutorial A brief discussion on the working principle of component styles in Angular

A brief discussion on the working principle of component styles in Angular

Jul 05, 2021 am 11:07 AM
angular

A brief discussion on the working principle of component styles in Angular

In the process of developing Angular components, we are used to writing the component styles in the corresponding css files, but we have never understood how Angular does it. Style isolation, for example, if h1 { color: red } is written in component A, this style will only take effect in component A and will not affect other components. In order to explore the principle, this article is created. The following content is based on Angular CLI version 10.1.1.

How component styles work

Explore

First create a new Angular project using Angular CLI and delete Replace all the content in app.component.html with the following content:

<h1 id="App-nbsp-Component">App Component</h1>
<button class="red-button">Button</button>
Copy after login

Add the following content in app.component.css:

.red-button {
  color: red;
}
Copy after login

Run There is the following html code:

<app-root _nghost-ydo-c11="" ng-version="10.1.1">
  <h2 id="App-nbsp-component">App component</h2>
  <button _ngcontent-ydo-c11="" class="red-button">Button</button>
</app-root>
Copy after login

You can see that there is a property named _nghost-ydo-c11 on the app-root element. The two elements inside app-root have an attribute named _ngcontent-ydo-c11. [Related tutorial recommendations: "angular tutorial"]

So what are these attributes used for?

For a better understanding, we first create an independent component and create a new file blue-button.component.ts with the following content:

import { Component } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-blue-button&#39;,
  template: `
    <h2 id="Blue-nbsp-button-nbsp-component">Blue button component</h2>
    <button class="blue-button">Button</button>
  `,
  styles: [`
    .blue-button {
      background: blue;
    }
  `]
})
export class BlueButtonComponent {}
Copy after login

Place it in ## After running in #app.component.html, you will see the following html code:

A brief discussion on the working principle of component styles in Angular

You can see

app-blue-button There is also an attribute that starts with _nghost-xxx, and another attribute that is the same as the other elements in app-root. Both elements in the component have attributes named _ngcontent-yke-c11.

Since the attribute strings generated by Angular are random each time it is run, if similar attributes appear in the subsequent code, they will correspond to this screenshot.

Summary

Through observation we can conclude:

    The host element of each component will be assigned a unique Attributes, depending on the processing order of the components, in the example is
  • _nghost_xxx
  • Each element in each component template will also be assigned an attribute unique to the component, in the example It's
  • _ngcontent_xxx
So how are these attributes used for style isolation?

These properties can be combined with CSS. For example, when we look at the style of the blue button in the example, we will see this css:

.blue-button[_ngcontent-yke-c11] {
    background: blue;
}
Copy after login

It can be seen that Angular uses this method The

blue-button class can only be applied to elements with this attribute, without affecting elements in other components.

Now that we know Angular’s ​​behavior of style isolation, how does Angular achieve this?

When the app starts, Angular will use the styles or styleUrls component properties to see which styles are associated with which components. Angular will then apply these styles and attributes unique to the elements in the component, wrap the generated css code in a style tag and put it in the header.

A brief discussion on the working principle of component styles in Angular

The above is the principle of Angular style encapsulation.

:host, :host-context, ::ng-deep

In actual development, this mechanism sometimes does not fully match our needs. In this case, Angular introduces several special selectors.

:host

Use the :host pseudo-class selector to act on the component (host element) itself.

For example, when we want to add a border to

app-blue-button, we can add the following code to the style of this component:

:host {
  display: block;
  border: 1px solid red;
}
Copy after login

By viewing the runtime In the code, you can see the following code block:

  <style>
    [_nghost-yke-c11] {
      display: block;
      border: 1px solid red;
    }
  </style>
Copy after login

:host-context

Sometimes, based on something from the component view

External Conditionally applied styles are useful. For example, there might be a CSS class representing a theme on the element of the document, and you should style the component based on that.

You can use the

:host-context() pseudo-class selector. It is also used in a form like :host(). It looks for CSS classes in the ancestor nodes of the current component's host element, up to the document's root node. It is very useful when combined with other selectors.

In the following example, which CSS will take effect will be determined based on whether the CSS class of the ancestor element is

blue-theme or red-theme.

import { Component } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-btn-theme&#39;,
  template: `
    <button class="btn-theme">Button</button>
  `,
  styles: [`
    :host-context(.blue-theme) .btn-theme {
      background: blue;
    }
    :host-context(.red-theme) .btn-theme {
      background: red;
    }
  `]
})
export class BtnThemeComponent { }
Copy after login

Then where it is used:

<div class="blue-theme">
  <app-btn-theme></app-btn-theme>
</div>
Copy after login

The button background is blue when running.

::ng-deep

我们经常会使用一些第三方 UI 库,有时候我们想改变第三方组件的一些样式,这时候可以使用 ::ng-deep,但是要注意,Angular 已经把这个特性标记为已废弃了,可能在未来的版本就被完全移除掉。

:host ::ng-deep h2 {
  color: yellow;
}
Copy after login

通过查看运行时的代码:

[_nghost-yke-c12] h2 {
    color: yellow;
}
Copy after login

可以看到,样式会作用在 app-root 里的所有元素上,包括 app-root 中使用的其他组件里的元素。

总结

在实际开发中,灵活使用以上几种方式,基本上可以满足大部分场景。

更多编程相关知识,请访问:编程教学!!

The above is the detailed content of A brief discussion on the working principle of component styles in Angular. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Let's talk about metadata and decorators in Angular Let's talk about metadata and decorators in Angular Feb 28, 2022 am 11:10 AM

This article continues the learning of Angular, takes you to understand the metadata and decorators in Angular, and briefly understands their usage. I hope it will be helpful to everyone!

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

Do you know Angular Universal? It can help the website provide better SEO support!

Angular + NG-ZORRO quickly develop a backend system Angular + NG-ZORRO quickly develop a backend system Apr 21, 2022 am 10:45 AM

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

What should I do if the project is too big? How to split Angular projects reasonably? What should I do if the project is too big? How to split Angular projects reasonably? Jul 26, 2022 pm 07:18 PM

The Angular project is too large, how to split it reasonably? The following article will introduce to you how to reasonably split Angular projects. I hope it will be helpful to you!

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

See all articles