This course has been updated! We now recommend you take the Angular 9 Fundamentals course.
Transcript from the "ng-if & else" Lesson
[00:00:00]
>> Lukas Ruebbelke: So what we could do is, and this is where we'll introduce another structural directive, is that in our project title here,what we can do is let's introduce and ngIf
>> Lukas Ruebbelke: So I do span,
>> Lukas Ruebbelke: ngIF, and let's just say,
>> Lukas Ruebbelke: If there is, and actually I apologize.
[00:00:41] Let me go down here, I'm in the wrong block here. Here we are, let's do this. So we'll go, we're at this in a span.
>> Lukas Ruebbelke: And then we're going to attach ngIf to this, so span.
>> Lukas Ruebbelke: ngIf, and we're just gonna say if there is a selectedProject, let's go ahead and do this.
[00:01:19] And so if selectedProject exists, then this is going to show. So you can actually take the safe navigation operator off. So one thing or common technique, generally, if I look at a template and there's just a turn of safe navigation operators, like does this exist and does this exist?
[00:01:39] I think that is kind of a sign that maybe you should do a higher level like does this thing even exist, if so then I'll show it. So this is a way to kind of keep from [INAUDIBLE] with some super verbose kind of DOM. I'll duplicate this line because we can say, well, if it doesn't exist then let's just go select project, or select a project.
[00:02:10]
>> Lukas Ruebbelke: Okay, save this. We'll go here, select a project. Selected. So if we go down here, what we really wanna do is if it doesn't exist, we wanna show something else. So we wrap it in an ng-template and then notice that we have this thing, it's an else block.
[00:02:41] But more importantly, what is this right here? So what this allows you to do is it's a local template variable, is that you can by using the pound sign, you can create a variable that references the element that this is on. So here we can go,
>> Lukas Ruebbelke: else.
[00:03:09] Was it elseif?
>> Lukas Ruebbelke: It's else.
>> Lukas Ruebbelke: Here elseBlock.
>> Lukas Ruebbelke: There we go. So this is, I believe, a lot cleaner than just stacking a bunch of like NgIfs turning it on and say if it's this or this. And so let me just summarize what's happened here. So, we took ngIf and we are saying instead of adding another ngIf for the else clause, that we are going to go else and then we're gonna say instead show this block here, else block.
[00:03:56] You would call this whatever you want. And then within a ng-template we are putting the code that we wanna see.
>> Lukas Ruebbelke: And then from here, elseBlock, and so this is how we're saying, if it's this, show what's in here. If not, take this content right here, and project it into here.
[00:04:18] And you're referencing it, you're connecting it via this local template reference.