In the angular project, if you use some plug-ins encapsulated in js, you need to manually introduce js files and css files. If you directly use the link method to introduce them on the application entry page, it will block the loading of the first screen and even cause redundancy. stylesheet; here's one way to reference external styles within a component.
First introduce an enumeration class of Angular:
enum ViewEncapsulation { Emulated Native None }
The value of ViewEncapsulation is used to specify how to handle the relationship between styles and tags when encapsulating Angular components. The default value is :ViewEncapsulation.Emulated;
Usage is:
import { ViewEncapsulation } from "@angular/core";@Component({ templateUrl: "./login.html", styleUrls: ['./login.css','/bootstrap/css/bootstrap.min.css'], encapsulation: ViewEncapsulation.Emulated })
When encapsulating a component in this way, it will assign a unique attribute to the component and add this attribute On each tag in the component, an attribute selector will be added to the selector of the encapsulated style sheet, thus forming a scope of the style sheet. The styles in the scope will not affect the outside, but the component will be affected by the parent style. The impact is as shown in the figure:
This method encapsulates the component into a shadow DOM;
The style sheet of this method has a global scope. The style declared in the component can affect not only this component, but also the global style sheet; in turn, the component has a global scope. The impact of style sheets.
Two situations:
1. The tags used by the external style sheet are static (such as bootstrap):
Introduced directly into the component metadata, using the default method:
@Component({ templateUrl: "./login.html", styleUrls: ['./login.css','/bootstrap/css/bootstrap.min.css'] })
2. Style sheets act on dynamically created tags (such as creating a rich text editor CKEditor, wangEditor, etc.):
Because tags are dynamically created, that is to say, when packaging components, introduce The tags used by the external style sheet do not yet exist (when the code is running, the tags will be created after a new Editor), but when packaging, an attribute selector is added to all selectors. Therefore, the dynamically created tags will not be created. Will be affected by imported style sheets. In other words, the newly created label does not belong to the scope of the component. In order to avoid this situation, you can only create a component for this component when packaging the component:
import { ViewEncapsulation } from "@angular/core";@Component({ templateUrl: "./login.html", styleUrls: ['./login.css','/bootstrap/css/bootstrap.min.css'], encapsulation: ViewEncapsulation.None})
The above is the detailed content of How to introduce external styles into Angular components. For more information, please follow other related articles on the PHP Chinese website!