angularjs topics

Total 1 topic

angular js
How to use ng-style in Angular Js.
In this short blog, we learn how to use 'ng-style' in AngularJS with a simple example. Following are the prerequisites: 1. Basic CSS (because ng-style is used to add styles). 2. Basic AngularJS (because you need to set up the AngularJS working environment). That's all for prerequisites. Let's start by talking about an example. Assume you have a list like below: <img src="https://meetprvt.github.io/blogassets/blogassets/ngstyle.png"> In the example, there are a few list elements with 'border-bottom' added. Now, as you can see, there is a 'border' on the very last element too, which does not look nice, and we also want to highlight the very first element with a different color border. So we have the following two requirements: • The last element in the list should not have a border. • The first element's border should be of a different color. To achieve the above requirements, we are going to use ng-style in our AngularJS project. 1. First, add ng-style to the element on which we want to add some conditional CSS. In our example, we are going to add ng-style="" next to ng-repeat. 2. If we are going to add any condition, we need to add '{}' inside our ng-style. After that, we need to specify our CSS properties inside '' in our case it's 'border' followed by ':'. 3. Now, after that, we need to specify our condition with the CSS property. As we want no border for the last list element, we are going to use ($last ? 'none' : ''). What this will do is, when it finds the last element, it will add 'none' to the border; otherwise, it will add null. 4. To add a different color border to the first element, we are going to use ""'border-color': ($first ? 'red' : '')"". What this will do is change the color of the border if it's the first element. The final code will be: <pre>ng-style=""{'border': ($last ? 'none' : ''), 'border-color': ($first ? 'red' : '') }""</pre> That's all; this is how we can use ng-style in AngularJS. You can add any desired CSS or conditions in ng-style, and if you want to play around, then use the codepen link below. Thank You.

© All right reserved by throughDev