Angular - 2.23- Improve ngIf with an Else condition
In the last course, we saw the basic syntax of NGIF, which is the syntax you will use most of the time. However, there is an alternative to this syntax. Sometimes you have not only the "if" condition, but also an "else" condition. So, in this example, we could say that the server was created and that serverName is something with NGIF. But we can also add an else block where we would like to say that no server has been created.
Now we have deleted this exact text for the reason that we don’t want to see it, but imagine that we wanted to show this alternative. So no server was created, it could be the text here, and now we want to show this paragraph only if NGIF is not true or if the "serverCreated" condition is not true. We can do this by placing a local reference on this element here.
The local reference is something I will explore further in the component understanding and data link sections. For now, let’s consider this element as a marker. I will therefore name this element "noServer" with a capital S. And now we have to change the paragraph here to ng model. This is a component, a shipping directive, with Angular that you can use to mark places in the MOD.
Now I’m going to add the paragraph in this template with the text in between, like this. So this is essentially the text you want to produce. And now with the ng model and the local reference marker we mark a certain place in the model that we want to display conditionally.
Now to view it conditionally, we simply improve NGIF by adding else and then noServer. So this marker is replaced in the ng model. And that’s all the syntax we need. If we save this, you see that no server was created and as soon as I click here, this is replaced by the server was created. So it’s NGIF else, a nice little addition in a use case where you have, well, an else condition.
Of course, the alternative would always be to simply use NGIF with reverse verification, so if the exclamation point server is created. But this is another interesting alternative. We will use this code in the course project we will build. I just wanted to point out that this option exists. However, the use of NGIF in this way is the most common case.