Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Anubhab Mukherjee
Anubhab Mukherjee

Posted on

     

Understanding Built In Angular Directives - Part 1

Today we will learn the built in directives Angular provides.
Before diving in we need to understand what is adirective.
As per Angular' s definition -

Directives are classes that add additional behavior to elements in your Angular applications

So now lets break it into simpler words to understand. A normal HTML element/ tag likeul li is used to show some text in bullet form. Eg.

<ul>    <li>83</li>    <li>32</li>    <li>66</li></ul>
Enter fullscreen modeExit fullscreen mode

will only display the text like below
Image description
It don't have any extra ability like adding CSS class or styles on the basis of a condition, show/ hide items on the basis of certain condition etc.
To give the normal HTML element an extra power the Angular introduced the concept of Directive. It is a class that does all the trick/ magic internally/ behind the scene.

So lets dive in to understand the various directives available in Angular.
There are broadly three different types of directives -

  • Component Directive - (Will talk about it at the very end)
  • Attribute Directive
    1. ngClass
    2. ngStyle
    3. ngModel
  • Structural Directive
    1. ngIf
    2. ngFor
    3. ngSwitch

Attribute Directives
Directives that changes the behavior of HTML element's attributes on which it has been used. Behavior includes CSS style CSS class etc.

ngClass
This directive adds or removes CSS class on the element it has been added to on the basis of a condition.
Lets see in practice.
Lets create a project and create a componentattributeDirectiveDemo. If you are not familiar about angular component or how to create one, I would suggest you to go through the below link -
Creating_Angular_Component

There are different syntax of using ngClass directive


a.Directly passing class name to the ngClass directive
[ngClass]="'<class name>'"
Step1 Add CSS classes to the css file
Image description
In the file showed with arrow in the above image lets put the below CSS code -

.success {  color: green;}.error {  color: red;}
Enter fullscreen modeExit fullscreen mode

These are two simple CSS classes namedsuccessanderror. When success class is used it will color the text green. While the error class will color the text with red.
Step2 Use the directive in the template/ HTML file
Now lets open the html file and paste the below code -

<div [ngClass]="'success'">Server One</div><div [ngClass]="'error'">Server Two</div>
Enter fullscreen modeExit fullscreen mode

Run the application and once you navigate to localhost:4200 you will see the below output -
Image description

Now lets understand the code we wrote in html file.
All the attribute directives are written inside a[] Square Bracket. The directive name is placed inside the square bracket. Then the equal= operator comes followed by the class name. The class namesuccess/erroris enclosed in double quotes" and single quote'.
Here the order of quotes is not important. You can also use

<div [ngClass]='"success"'>Server One</div>
Enter fullscreen modeExit fullscreen mode

But you should not be writing like below code -
Image description
If you just use a pair of double quotes and write the class name inside it like below -

<div [ngClass]="success">Server One</div>
Enter fullscreen modeExit fullscreen mode

Then Angular will think success as a variable/ property present in the component ts file and will throw error and not work as expected.


b.Applying a CSS class on the basis of a condition

[ngClass]="{ <class_name>: <condition> }"

Step1
Now, lets open the component typescript file and add a variable
serverOneStatus and initialize it with the valueup.
Image description
Step2
Now, lets open the component html file and type in the below code -

<div [ngClass]="{ success: serverOneStatus === 'up' }">Server One</div>
Enter fullscreen modeExit fullscreen mode

Now once you open the application in browser you will see the below output. The text is becoming green so the success class is getting correctly applied.
Image description
So, here in the above code we are checking if the variableserverOneStatus has a value ofup (Remember we initialized the variable serverOneStatus in the TS file with the value up) i.e. the condition evaluates to true then the corresponding CSS classsuccess will be applied else the CSS class wont be applied.


c.Applying Multiple Condition
We can also pass multiple condition to ngClass directive
[ngClass]="{
<Class_1>: <Condition_1>,
<Class_2>: <Condition_2>
}"

So, here we are adding one more class along with the condition separated by a,. Depending on which condition evaluates to true the corresponding class will be applied. If both the condition results to true then both the class will be applied.
Lets see how it can be implemented in our code -

<div  [ngClass]="{    success: serverOneStatus === 'up',    error: serverOneStatus === 'down'  }">  Server One</div>
Enter fullscreen modeExit fullscreen mode

So here we added an extra class and an extra condition
error: serverOneStatus === 'down'
Now lets understand the whole stuff - if the variableserverOneStatus has a valueup then the success class will be appended and if the variable holds a valuedown then the error class will be appended to the element on which ngClass is used, here in this casediv.


d.Passing Ternary operator to ngClass
We can also pass condition by using ternary operator.
[ngClass]="<codition> ? <'Class_Name1'> : <'Class_Name2'>"
So, now lets open the component html file and add the below code -

<div [ngClass]="serverOneStatus == 'up' ? 'success' : 'error'">Server One</div>
Enter fullscreen modeExit fullscreen mode

Here we are passing a ternary operator. We are checking a condition if the conditionserverOneStatus == 'up' evaluates to true then the success class will be appended else error.

Now if you see in browser you will see the text is colored green.

That's all in this part.
In this section we learnt the basic concept of directives, different built-in directives available in Angular and ngClass in detail.
Will cover the remaining directives in the upcoming posts.
Stay Tuned...
If you liked the post do like and comment.

Cheers!!!
Happy Coding

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
giacorsa profile image
Gianni
  • Joined

hi Anubhab,
is there part 2, part 3 and so on about Understanding Built In Angular Directives? i don't see link to them ...
anyway, many congratulations for this precious article,
by Gianni

CollapseExpand
 
anubhab5 profile image
Anubhab Mukherjee
I am a JS enthusiast. Love to talk on any topics related to Angular, Javascript, CSS3
  • Location
    India
  • Joined

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I am a JS enthusiast. Love to talk on any topics related to Angular, Javascript, CSS3
  • Location
    India
  • Joined

More fromAnubhab Mukherjee

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp