3

flow:

  1. User submits a form with some data, some optional fields that the user didn't fill are saved in mongo as 'null'.
  2. Later on, user decides to edit that form.
  3. Service grabs the form and displays it to the user.
  4. The form input boxes displays 'null' because in step 1 he didn't fill them.

So, I created a pipe:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
name: 'transformNull'
 })

export class TransformNull implements PipeTransform {

transform(value) {
if (value == null) {
  return null;
 }
}

Then, in HTML I tried to break down the ngModel:

[ngModel]="user.extraInfo | transformNull" (ngModelChange)="user.extraInfo.value=$event"

this caused this error:

Cannot set property 'value' of undefined TypeError: Cannot set property 'value' of undefined

I tried to delay the page load with an *ngIf="isDataAvailable", the error went away, the user can save the form, the value gets stored to mongo but when he refreshes the page, the input box is empty.

Then i removed the *ngIf, added elvis operators but the value error comes back.

I'm using zone.js v0.7.4, tried with 0.7.2 and 0.7.5 but no luck.

What am I missing here?

Jim
  • 3,821
  • 1
  • 28
  • 60
Stathis Ntonas
  • 1,222
  • 2
  • 20
  • 49
  • Did you check https://stackoverflow.com/questions/36016407/two-way-binding-with-elvis-operator/36016472#comment70500052_36016472? – eko Jan 16 '17 at 14:59
  • how about: (ngModelChange)="user.extraInfo = $event" and please remove your pipe "transformNull" – Saeed Jan 17 '17 at 06:32
  • @SaeedPy removed pipe, change the part you mention, still null in input box. – Stathis Ntonas Jan 17 '17 at 11:49
  • i changed the `if (value == null)` to `if(value === 'null')` and added an `else { return value}` to the pipe. Then i used this in html: `[ngModel]="user.extraInfo | transformNull" (ngModelChange)="user.extraInfo.value = $event"` and it worked. I' using Resolver on router now and the component loads after data has arrived. – Stathis Ntonas Jan 17 '17 at 12:42

1 Answers1

8

With ngModel it needs to be split into

[ngModel]="user?.extraInfo " (ngModelChange)="user.extraInfo = $event"
Saeed
  • 3,415
  • 3
  • 24
  • 41
  • I had an exception, because my binding targed was null. But thanks to your proposal, it works perfectly now. – peter70 Jul 03 '17 at 13:20