Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ngSwitch on datatype in angular?

I was working in angular2 and was curious to know whether I could use ngSwitch to load <div> tag when variable is of certain datatype.i.e. something like this:

 <div [ng-switch]="value">
  <p *ng-switch-when="isObject(value)">This is Object</p>
  <p *ng-switch-when="isArray(value)">This is Array</p>
  <p *ng-switch-when="isBoolean(value)">This is Boolean</p>
  <p *ng-switch-when="isNumber(value)">This is Number</p>
  <p *ng-switch-default>This is Simple Text !</p>
</div>

is this possible to load the div tag when variable is of certain datatype? if not, any workaround for this?

like image 364
Bhushan Gadekar Avatar asked Jun 24 '16 12:06

Bhushan Gadekar


People also ask

What is the use of ngSwitch in angular?

AngularJS ng-switch Directive The ng-switch directive lets you hide/show HTML elements depending on an expression. Child elements with the ng-switch-when directive will be displayed if it gets a match, otherwise the element, and its children will be removed.

What is the difference between NgIf and ngSwitch?

The important difference between the ngIf solution is that through NgSwitch we evaluate the expression only once and then select the element to display depending on the result. Using ngIf we can conditionally add or remove an element from the DOM.


1 Answers

An alternative would be to use ngIf:

  <p *ngIf="isObject(value)">This is Object</p>
  <p *ngIf="isArray(value)">This is Array</p>
  <p *ngIf="isBoolean(value)">This is Boolean</p>
  <p *ngIf="isNumber(value)">This is Number</p>
  <p *ngIf="!isObject(value) || !isArray(value) || !isBoolean(value) || !isNumber(value)">This is Simple Text !</p>
like image 122
null canvas Avatar answered Oct 28 '22 06:10

null canvas