0

My JSON looks like this:

[
 {
   "firstName": "tom",
   "lastName": "null",
   "phone": "null",
   "status": "Active",
 },
 {
   "firstName": "Bob",
   "lastName": "null",
   "phone": "null",
   "status": "Inactive",
 }
]

I am displaying the 2nd property(i,e lastName) of the JSON object like this:

  <div class="form-group" >
      <label>Last Name</label>
      <input  class="form-control" [(ngModel)]="customer.lastName">
  </div>

Since its value is null it displays as null , Here i need to write condition like this:

If the properties(lastName,phone... ) value is null in the input it should not display anything,but input should to visible to the user.

SGR
  • 191
  • 2
  • 4
  • 12
  • Its value is not `null`. Its value is the string `"null"`. Fix your JSON. Once fixed, everything will work fine: https://stackblitz.com/edit/angular-vc9nhd?file=src%2Fapp%2Fapp.component.ts – JB Nizet Jul 12 '19 at 10:13
  • While creating the customer object,Intentionally we store `lastName`(type:string) as `null`. – SGR Jul 12 '19 at 10:19
  • I am looking for this **https://stackoverflow.com/questions/45476141/how-to-hide-null-in-the-input-field-angular-2** – SGR Jul 12 '19 at 10:24
  • you design is severely broken. You're using a special string `"null"` (i.e. the 4 letters n, ul, l, l), instead of the literal null, which means "the absence of a value. Fix that. You won't be able to do anything clean and correct using that design. And what if someone's last name is actually "null"? – JB Nizet Jul 12 '19 at 10:33
  • Thanks for the guidance,I will fix it.I will use literal null instead of special string "null", Even for the literal how can i write the condition? – SGR Jul 12 '19 at 10:36
  • You don't need to do anything special if you correctly use null. See my first comment. – JB Nizet Jul 12 '19 at 10:38

1 Answers1

2

You can achieve this just using Conditional (Ternary) Operator in your ng model like below.

<div class="form-group" >
      <label>Last Name</label>
      <input  class="form-control" [(ngModel)]="customer.lastName === 'null' ? '' : customer.lastName">
  </div>
Dheeraj Kumar
  • 146
  • 1
  • 10
  • No, that wouldn't be valid. Angular needs to **update** the value of the expression, and this expression is not writeable. – JB Nizet Jul 12 '19 at 11:01
  • @JBNizet There is no need of updating angular. Ng Model is accepting the condition's from Angular 2. Please check https://stackoverflow.com/questions/45144230/conditional-ngmodel-in-angular2 for your reference. – Dheeraj Kumar Jul 12 '19 at 11:06
  • See https://stackblitz.com/edit/angular-a7bti4?file=src%2Fapp%2Fapp.component.html. – JB Nizet Jul 12 '19 at 12:12