3

I have this form component that takes as input an User object. I want to use that object for two way data binding but it doesn't work. Any ideas where is the problem ?


PS: The problem seems to come from the copying of the input parameter. If I pass the original it works fine, but if I pass a copy the two way data binding does not work. How can I make it work with the copy?

<user-form [selectedUser]="copyUser()" (isValidated)="onToggleDialog($event)"></user-form> 


copyUser() :User {
  // when returning the copy it doesn't work, 
  // but when returning this.userToPass it works 
  return JSON.parse(JSON.stringify(this.userToPass));
}

import { Component, EventEmitter } from '@angular/core';

import {
    FormBuilder,
    FormGroup,
    Validators,
    AbstractControl,
    ReactiveFormsModule 
 } from '@angular/forms';

import { User } from '../../domain/user';
import { GlobalMailValidator } from '../../validators/mail/mail.validator';
import { Role } from '../../domain/role';
import { UserService } from '../../services/user.service';

 @Component({
     inputs: ['selectedUser'],
     outputs: ['isValidated'],
     selector: 'user-form',
     templateUrl: 'app/component/user/user.form.html'
 })
 export class UserForm {

     /**
      * The user passed to this component. It should preferably be a copy.
      */
     selectedUser: User;

     /**
      * All the roles in the DB.
      */
     roles: Role[];

     /**
      * All the time zones in the DB.
      */
     timeZones: any[];

     /**
      * Event emitter to output the edited user.
      * Returns null if the operation was canceled.
      */
     isValidated: EventEmitter<User>;

     constructor(private userSerive: UserService) {

        this.isValidated = new EventEmitter();
        // instantiate the roles array only ones on component creation
        this.userSerive.listRoles().then( res => this.roles = res);
        this.userSerive.listTimeZones().then( res => this.timeZones = res);
    }

    assessValidation(success: boolean) :void {
        // the selected user object does not change :(
        console.log(this.selectedUser);
        if(success) {
            //this.isValidated.emit(this.selectedUser);
        } else {
            // if a cancel operation was requested emit null instead
            this.isValidated.emit(null);
        }

    }

 }

<!-- THIS DOES NOT UPDATE !!!! -->
<div>{{selectedUser.firstName}}</div>
<form #controlForm="ngForm">
            <div class="ui-g">
                    <input type="text"
                           placeholder="Login"
                           [(ngModel)]="selectedUser.login"
                           name="login"
                           #login="ngModel"
                    />      
            </div>
            <div class="ui-g">
                <input  type="text" 
                        placeholder="First Name"
                        [(ngModel)] = "selectedUser.firstName"
                        name="firstName"
                        #firstName="ngModel"
                />
            </div>
            <div class="ui-g">
                <input  type="text"
                        placeholder="Last Name"
                        [(ngModel)] = "selectedUser.lastName"
                        name="lastName"
                        #lastName="ngModel"
                />
            </div>            
            <div class="ui-g">
                <input  type="text"
                        placeholder="e-mail"
                        [(ngModel)]="selectedUser.email"
                        name="email"
                        #email="ngModel"
                />
            </div>

            <div class="ui-g">
                    <input type="checkbox" [(ngModel)]="selectedUser.isDeleted" name="isDeleted" #isDeleted="ngModel"/>
            </div>

            <button type="button" [disabled]="!controlForm.form.valid" class="ui button" (click)="assessValidation(true)">Save</button>
            <button type="button" class="ui button" (click)="assessValidation(false)">Cancel</button>
</form>

import { Role } from '../domain/role';

export class User {
  fullName: string;
  password: string;
  isDeleted: boolean = false;

  constructor(public id: number, 
      public login:string,       
      public firstName:string, 
      public lastName:string, 
      public email:string, 
      public locale:string, 
      public timeZone:string,
      public version:number,
      public roles:Role[]) { 
    this.fullName = this.firstName + ' '  + this.lastName;    
  }
}

export class Role {
  id: number;
  name: string;
  refId: string;
}
3
  • You don't need #firstName if you are already using [(ngModel)] Commented Dec 21, 2016 at 8:35
  • @zurfyx This does not solve the problem :( Commented Dec 21, 2016 at 8:37
  • try it once using selectedUser?.firstName , also from where the data is coming in selectedUser ? Commented Dec 21, 2016 at 8:39

1 Answer 1

0

You have to initialize the user object first.

selectedUser: User = new User();
Sign up to request clarification or add additional context in comments.

5 Comments

This does not solve the problem. It still doesn't update. The passed object is a copy of the original : <user-form [selectedUser]="copyUser()" (isValidated)="onToggleDialog($event)"></user-form> copyUser() :User { return JSON.parse(JSON.stringify(this.selectedUser)); }
@user3719857 Can you try with a [(ngModel)] with a simple string on the same component and see if it works for you?
All you need is to correctly initialize User then, can you edit your initial question with your user.ts?
@user3719857 Does it work with fullName? Actually, I don't think there's any need to have them with public like you do so in the constructor. I would leave the constructor empty and have a get fullName() { return ${firstName} ${lastName}` }`
No it does not work with fullName. I'm going to try with an empty constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.