Angular Directives — #3

Rafael Neves
angularbr
Published in
4 min readApr 1, 2022

--

Hey folks,

Let's talk in this chapter about Angular Directives.

Introduction

Directives are like markers on DOM element that communicate to Angular to include a specific behavior.
There three types of directives on Angular:

Attributes directives: Change the appearance or the behavior of an element, component or another directive, as ngClass and ngStyle;

Structural directives: Modify the layout adding or removing DOM elements, as ngIf and ngFor;

Components: Are directives with a model

Starting the app on your terminal:

ng new diretivasPoc

Let's create a app that we can know a bit the directives that we will talk on this article:

Begin with ngIf:

It is a directive that allow us to change a page from a conditional declaration and that supposed to mean that put a ngIf in an element or component we can create or remove this element in the condition we provide:

To sum up convert a furnished value to an equivalent to true or false…after decides if show or not the element.

ngSwitch

It is a directive that show an element of a group in basis of a condition. It uses the directives ngSwitchCase and ngSwitchDefault:

Set a variable and uses in .html and setup below.

ngswitch.compoent.ts
ngswitch.compoent.html

The result will be something like this:

http:localhost:4200

ngFor

Do you know when we view a table list with a lot of information?
This happens with the help with a repetition loop that create all data one by one…
So the ngFor is a right tool to have on your sleeve.
How use the tool?

As below, we have a list to iterate:

ngfor.component.ts

We can present the data as a list or in a table list:

ngfor.component.html

Look how we see this:

http:localhost:4200

ngClass

It is a directive that allows you define a class dynamically from Dom element.
Let's on real how works:

ngclass.component.ts
ngclass.component.html

Note that if !isFavorite show the icon (bi-star), else isFavorite (bi-star-fill)

http://localhost:4200

ngStyle

It is used to add style in DOM element, look bellow:

ngstyle.component.ts

On this example, I was far away using Inputs two way data binding to change the color font and size:

ngstyle.component.html
http://localhost4200

And this is it guys, this is a resume of how works with this basics directives. Considerer that we have too custom directives that allows you to create your own rules.
Take a look on my Github on this repo.

See you all on the next….byeee

--

--

Rafael Neves
angularbr

Desenvolvedor de sistemas, apaixonado por tecnologia e novos aprendizados. Compartilhando insights no Medium.