Introduction to Structural Directives
Let’s learn the fundamentals of structural directives.
We'll cover the following
In this chapter, we’ll focus on structural directives. The main difference between structural and attribute directives is that structural directives change the actual DOM structure, while attribute directives just change the appearance of existing DOM elements.
Structural directives define the DOM structure by simply adding or removing elements in the DOM. This is very important to understand because structural directives receive a template that seems to be an actual DOM element. But, as a matter of fact, it’s not a DOM element at all. It’s just a virtual template. The directive uses this template to create a view which is then pushed to the DOM.
In this lesson, we focus more on theory so that we can learn the basics. In the next lesson, we focus on actual implementation. It’s crucial to understand the fundamentals because they allow us to think about templates and elements from a new perspective.
Later, we’ll learn the difference between an actual element, an Angular template, and a view. This will be helpful when we implement custom structural directives.
Introduction to templates and views
When we worked with attribute directives in the last lesson, we learned about a useful technique where we get an instance of ElementRef
in our directive that pointsto an actual element in the DOM.
When working with structural directives, we need to think differently. This is because, in this case, there is no element. How is that possible?
Templates
Let’s learn about template usage with the NgIf
directive. Let’s begin by looking at how *ngIf
is applied to an element below:
<div *ngIf="true"> Hi, I'm visible </div>
Angular doesn’t render this <div>
element by default. Instead, it uses <div>
as a template. We’ll learn how Angular does this later in the course.
What does it mean that Angular uses it as a template? It means that the following element is not added to the DOM by default:
<div> Hi, I'm visible </div>
Instead, this element is stored as a template so it can initiate embedded views later. In this example, it’s initiated when the NgIf
statement is true
.
To access the stored template, we use a TemplateRef
instance. Whenever we apply a directive to the ng-template
element, we get access to that element through TemplateRef
.
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy