ngIf with Angular 2 and TypeScript - lishman.io
lishman.io Loading..
Style: Blog or IDE

ngIf with Angular 2 and TypeScript

The ngIf directive adds and removes elements in the DOM based on the results of an expression.

Updated Jan 2017, Angular version 2.4.x

Quick Tip

Also, take a look at the IDE style to see this tutorial in wide-screen mode. You can always switch back using the Style link at the top of the page.

Show me the IDE style

First Example

The ngIf directive in this code will add or remove the div element depending on the expression in quotes.
HighlightClick here to highlight the expression that is being evaluated.

ng-if.component.ts x
Loading...

Second Example

These ngIf directives will add or remove the <h3> and <p> elements depending on the checked properties of the big and small reference variables.

ng-if.component.ts x
Loading...

The Application

Here is the output from this component.

Loading...

Where Next?

More Directives

To learn more about the other built-in directives, take a look at these tutorials.

  • ngSwitch displays one element (and its children) from a set of possible options, based on some condition.
  • ngFor is a repeater directive which outputs a list of elements by iterating over an array.
  • ngClass adds and removes CSS classes on an element.
  • ngStyle sets CSS styles on an HTML element conditionally.