The Built-in `NgIf` Directive
Let’s learn about `NgIf`, a built-in attribute directive.
We'll cover the following...
The if
statement is probably one of the most recognizable keywords in most programming languages. However, there’s no if
statement in HTML.
The ability to complete tasks conditionally is essential for creating dynamic applications. From the front-end perspective, this means the ability to show or hide part of the view. So, the NgIf
directive fills this gap and provides an implementation of the if
statement for HTML templates.
The NgIf
syntax
The structural directive NgIf
can be correctly applied to an element by using the *
syntax. The asterisk indicates that the directive should be treated as structural one by Angular. We’ll learn more about this syntax later.
NgIf
works according to a statement we need to provide. If it’s true
, the element is visible on a page. If it’s false
, it is hidden.
<div *ngIf="true"> Hello there, I'm visible! </div>
<div *ngIf="false"> and I'm hidden </div>
Let’s check this example:
@Component({
selector: 'app-user',
template: `<p *ngIf="signIn">Hello John!</p>`,
})
export class UserComponent implements OnInit {
signIn = false;
constructor(private authService: AuthService){}
ngOnInit() {
this.signIn = this.authService.isUserSignIn();
}
}
In this case, we have a signIn
boolean property that takes a true
or false
value based on the result of the service call. In this scenario, if a user is signed into the application, they’ll see a greeting message and if the user is not authorized, they’ll see nothing.
Let’s go even further. The NgIf
directive not only accepts boolean values, but also accepts all valid expressions that might be evaluated as boolean values. So, it accepts almost everything. Therefore, we can pass strings, numbers, enum values, arrays, objects, function calls, and more to NgIf
. ...