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

青灯夜游
Release: 2021-07-08 11:20:03
forward
2030 people have browsed it

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

In the process of developingAngular 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, ifh1 { 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 deleteReplace all the content in app.component.htmlwith the following content:

App Component

Copy after login

Add the following content inapp.component.css:

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

Run There is the following html code:

 

App component

Copy after login

You can see that there is a property named_nghost-ydo-c11on theapp-rootelement. The two elements insideapp-roothave 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 fileblue-button.component.tswith the following content:

import { Component } from '@angular/core'; @Component({ selector: 'app-blue-button', template: ` 

Blue button component

`, 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-buttonThere is also an attribute that starts with_nghost-xxx, and another attribute that is the same as the other elements inapp-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-buttonclass 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:

Copy after login

:host-context

Sometimes, based on something from the component view

ExternalConditionally applied styles are useful. For example, there might be a CSS class representing a theme on theelement 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 theancestor nodesof 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-themeorred-theme.

import { Component } from '@angular/core'; @Component({ selector: 'app-btn-theme', template: `  `, 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:

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!

Related labels:
source:juejin.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!