【问题标题】:Two way data binding in form doesn't work Angular 2表单中的两种方式数据绑定不起作用Angular 2
【发布时间】:2016-12-21 19:39:07
【问题描述】:

我有一个将User 对象作为输入的表单组件。我想将该对象用于双向数据绑定,但它不起作用。任何想法问题出在哪里?


PS:问题似乎来自输入参数的复制。如果我通过原始它工作正常,但如果我通过一个副本,两种方式的数据绑定不起作用。我怎样才能使它与副本一起使用?

<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;
}

【问题讨论】:

  • 如果您已经在使用[(ngModel)],则不需要#firstName
  • @zurfyx 这并不能解决问题:(
  • 使用selectedUser?.firstName 尝试一次,同样来自selectedUser 的数据来源?

标签: angular


【解决方案1】:

你必须先初始化用户对象。

selectedUser: User = new User();

【讨论】:

  • 这并不能解决问题。它仍然没有更新。传递的对象是原始对象的副本: copyUser() :User { return JSON.解析(JSON.stringify(this.selectedUser)); }
  • @user3719857 你能尝试在同一个组件上使用[(ngModel)] 和一个简单的string,看看它是否适合你?
  • 您只需要正确初始化User 然后,您可以用user.ts 编辑您的初始问题吗?
  • @user3719857 它可以与 fullName 一起使用吗?实际上,我认为没有必要像在构造函数中那样将它们公开。我会将构造函数留空并有一个get fullName() { return ${firstName} ${lastName}` }`
  • 不,它不适用于 fullName。我将尝试使用一个空的构造函数。
猜你喜欢
  • 1970-01-01
  • 2015-11-07
  • 1970-01-01
  • 2018-08-06
  • 2018-09-15
  • 1970-01-01
  • 2017-04-06
  • 2019-06-27
  • 1970-01-01
相关资源
最近更新 更多