2017-07-05 18 views
0

我有一个基本的角度组件,允许某个用户在他们转到他们的配置文件并单击“编辑”后编辑用户的详细信息。Angular - 从服务重新填充表单输入

组件:

export class EditUserComponent implements OnInit { 

    // Define our vars 
    user: Users[]; 
    editUserForm: FormGroup; 
    message: {}; 
    displayMessage = false; 
    userID: number; 
    errorMessage: any = ''; 

    constructor(
     private fb: FormBuilder, 
     private _userService: UserService, 
     private activatedRoute: ActivatedRoute 
    ) { 
    } 

    ngOnInit(): void { 

     // Get the userID from the activated route 
     this.activatedRoute.params.subscribe((params: Params) => { 
      this.userID = params['id']; 
     }); 

     // Call our service and pass the UserID 
     this._userService.getUser(this.userID) 
      .then(res => { 
       this.user = res; 
       this.createForm(); 
      }); 

    } 

    // Generate the form 
    createForm() { 
     this.editUserForm = this.fb.group({ 
      QID: ['', Validators.required], 
      favoriteColor: [''], 
      favoriteNumber: [''], 
      favoriteActor: [''] 
     }); 
    } 

} 

服务:

// Fetch a single user 
    getUser(userID: number) { 
     return this._http.post(this.baseUrl + '/fetchUser', { "userID": userID }, { "headers": this.headers }) 
      .toPromise() 
      .then(res => res.json()) 
      .catch(err => { this.handleError(err); }); 
    } 

接口:

export interface Users { 
    RecordID?: number; 
    QID: string; 
    favoriteColor?: string; 
    favoriteNumber?: number; 
    favoriteActor?: string; 
} 

我试图通过值给我的formGroup,但我无法弄清楚如何访问这些值。

我认为我可以做这样的事情,我可以访问用户模型,并从中选择一个属性,但是抛出一个未定义的错误。

我会在表单组中传递值,还是直接以某种方式将它们绑定到元素上?我正好从服务中收到数据,只是不确定如何将每个值返回到各自的字段。

createForm() { 
    this.editUserForm = this.fb.group({ 
     QID: [this.user.QID, Validators.required], 
     favoriteColor: [''], 
     favoriteNumber: [''], 
     favoriteActor: [''] 
    }); 
} 

回答

1

如果我理解正确的...这是我的代码如下所示:

onProductRetrieved(product: IProduct): void { 
    if (this.productForm) { 
     this.productForm.reset(); 
    } 
    this.product = product; 

    // Update the data on the form 
    this.productForm.patchValue({ 
     productName: this.product.productName, 
     productCode: this.product.productCode, 
     starRating: this.product.starRating, 
     description: this.product.description 
    }); 
    this.productForm.setControl('tags', this.fb.array(this.product.tags || [])); 
} 

我对数值使用patchValue,对数组使用setControl

OR

由于您检索数据后创建的形式,你可以做这样的事情:

createForm() { 
    this.editUserForm = this.fb.group({ 
     QID: [this.user.QID, Validators.required], 
     favoriteColor: [this.user.favoriteColor], 
     favoriteNumber: [this.user.favoriteNumber], 
     favoriteActor: [this.user.favoriteActor] 
    }); 
} 

,只是要完整...每个输入元素需要一个formControlName性质类似这样的:

    <input class="form-control" 
          id="productNameId" 
          type="text" 
          placeholder="Name (required)" 
          formControlName="productName" /> 
        <span class="help-block" *ngIf="displayMessage.productName"> 
          {{displayMessage.productName}} 
        </span> 
       </div> 

您可以在这里找到一个完整的工作示例:https://github.com/DeborahK/Angular2-ReactiveForms

+0

所以你的第二个使用'this.user.QID'的例子是我理想的解决方案,并且是我首先尝试的,但是我在'Users []'类型'中找不到'Property'QID'的错误。“我认为它是正确的,因为它在我的界面中定义。 – SBB

+0

这正是它所说的吗?如果是这样,那么它认为'this.user'是一个数组。你是否从'getUser'获得数组而不是获取单个用户? – DeborahK

+0

噢......我看到了......你把它声明为一个顶部数组:'user:Users [];'如果它不应该是一个数组,那么将它改为'user:Users'(没有数组)。 – DeborahK

0

绑定一个事件提交到表单,然后使用this.editUserForm.value从表单访问数据。

分量模板:

<form [formGroup]="editUserForm" (submit)="saveIt()"> 

在Component:

saveIt() { 
    if (this.editUserForm.dirty && this.editUserForm.valid) { 
     alert(`Number: ${this.editUserForm.value.favoriteNumber} Actor: ${this.editUserForm.value.favoriteActor}`); 
    } 
    } 
+0

这看起来像反应形式...所以没有必要从模板中传递它。 – DeborahK

+0

我不想让输入的值进入表单。该页面有几个输入字段,我需要从数据库中填写(服务调用),以便可以更新它们。本质上,我将这些字段的值设置为从数据库中提取的值。 – SBB