...

/

The Built-in `NgIf` Directive

The Built-in `NgIf` Directive

Let’s learn about `NgIf`, a built-in attribute directive.

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:
...