Home >Web Front-end >JS Tutorial >Angular learning detailed explanation of the use of style binding (ngClass and ngStyle)
In front-end development, we often encounter such a situation: different pages are shared For the same piece of code, at the same time, we need to decide whether to display this code or make certain changes to the page style based on the specific information of the page or a certain operation (such as clicking a button). At this time, we use angular Style binding in !
For example: Two pages of the website need to use the same piece of code. Writing it twice is not consistent with dry (don't repeat yourself) principle, the efficiency is also very low, so this is usually not done in Angular front-end development projects in the company. If one day your leader tells you: zzz, please change the code. With this prompt, I want this effect on this page and that effect on another page. What should you do? Below is a simple example to illustrate. [Related tutorial recommendations: "angular tutorial"]
Common code snippets (before modification):
<div class="normalTxt"> <span >I love angular</span> </div>
Style binding in angular can achieve the above requirements. Angular has two style binding instructions: [ngStyle], [ngClass]
Note: They must be enclosed in [ ] square brackets when using!
1.[ngStyle]
<any [ngStyle]=“obj”>
Instructions:
Simple usage (html file):
//将这段div的背景色改为绿色 <div [ngStyle]="{'background-color':'green'}"> xxxx </div>
Complex usage (html file):
//如果当前页面为主页则将背景色改为绿色,否则改为红色 <div [ngStyle]="{'background-color':pageName== 'homepage' ? 'green' : 'red' }"> xxxx </div>
2.[ngClass]
<any [ngClass]=“obj”>
Note:
Simple usage (html file):
//使用.homepageText样式 <div [ngClass]="{'homepageText':true}"> xxxx </div>
Complex usage (html file):
//当页面名称是homepage时使用.homepageText样式,否则不使用 <div [ngClass]="{'homepageText':pageName =='homepage'}"> xxxx </div>
(css file):
.homepageText { font-size: 14px; font-weight: bold; }
The following is the solution to the beginning problem, I hope it can bring you some inspiration
Common code snippets (modification After):
f4d511afc8efca1bd60a437c643cdd97 45a2772a6b6107b401db3c9b82c049c2I love angular54bdf357c58b8a65c66d7c19c8e4d114 16b28748ea4df4d9c2150843fecfba68
Description: The portal page wants to show the effect of normalTxt, and the detail page wants to show the effect of specialTxt. The specific styles of normalTxt and specialTxt need to be added in the corresponding .css/.scss files.
For more programming-related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of Angular learning detailed explanation of the use of style binding (ngClass and ngStyle). For more information, please follow other related articles on the PHP Chinese website!