Deciding what to display on the screen for a user is a common task in application development. Many times, the decision is made programmatically using conditions.
To express conditional displays in templates, Angular uses the @if
template syntax.
In this activity, you'll learn how to use conditionals in templates.
The syntax that enables the conditional display of elements in a template is @if
.
Here's an example of how to use the @if
syntax in a component:
@Component({ ... template: ` @if (isLoggedIn) { <p>Welcome back, Friend!</p> } `,})class AppComponent { isLoggedIn = true;}
Two things to take note of:
- There is an
@
prefix for theif
because it is a special type of syntax called Angular template syntax - For applications using v16 and older please refer to the Angular documentation for NgIf for more information.
-
Create a property called
isServerRunning
In the
AppComponent
class, add aboolean
property calledisServerRunning
, set the initial value totrue
. -
Use
@if
in the templateUpdate the template to display the message
Yes, the server is running
if the value ofisServerRunning
istrue
. -
Use
@else
in the templateNow Angular supports native template syntax for defining the else case with the
@else
syntax. Update the template to display the messageNo, the server is not running
as the else case.Here's an example:
template: ` @if (isServerRunning) { ... } @else { ... }`;
Add your code to fill in the missing markup.
This type of functionality is called conditional control flow. Next you'll learn how to repeat items in a template.