


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>
Add the following content in app.component.css
:
.red-button { color: red; }
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>
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 '@angular/core'; @Component({ selector: 'app-blue-button', 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 {}
Place it in ## After running in #app.component.html, you will see the following html code:
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
- _ngcontent_xxx
.blue-button[_ngcontent-yke-c11] { background: blue; }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.
: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 toapp-blue-button, we can add the following code to the style of this component:
:host { display: block; border: 1px solid red; }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>
:host-context
Sometimes, based on something from the component viewExternal 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.
blue-theme or
red-theme.
import { Component } from '@angular/core'; @Component({ selector: 'app-btn-theme', 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 { }Then where it is used:
<div class="blue-theme"> <app-btn-theme></app-btn-theme> </div>The button background is blue when running.
::ng-deep
我们经常会使用一些第三方 UI 库,有时候我们想改变第三方组件的一些样式,这时候可以使用 ::ng-deep,但是要注意,Angular 已经把这个特性标记为已废弃了,可能在未来的版本就被完全移除掉。
:host ::ng-deep h2 { color: yellow; }
通过查看运行时的代码:
[_nghost-yke-c12] h2 { color: yellow; }
可以看到,样式会作用在 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!

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),