如何将值从数组分配给模型

时间:2019-08-22 14:52:39

标签: arrays angular ngmodel

从数组分配给模型时遇到问题。我想从userFromDb分配firstName值,并将此值分配给模型中的firstName,并与另一个值相同。我不知道怎么做:(

  

用户

export interface User{

id:string;
firstName:string;
lastName:string;
email:string;
password:string;
}
  

UpadateUserComponent.ts

userFromDb: Array<Object>;

model:User = {
id: '',
firstName: '',
lastName: '',
email: '',
password: ''}

ngOnInit() {

let id = this.route.snapshot.paramMap.get('id');

this.userService.getUser(id).subscribe(result => {
  console.log(result)
  this.userFromDb = result
  console.log(this.userFromDb)
});
  

UpadateUserComponent.html

<div>
    <form action="" #f="ngForm" (ngSubmit)="saveUser()" novalidate>
        <div>
            <label for="firstName">First Name: </label>
            <input [(ngModel)]="model.firstName" type="text" id="firstName" name="firstName" placeholder="Name">
        </div>
        <div>
            <label for="lastName">Last Name: </label>
            <input [(ngModel)]="model.lastName" type="text" id="lastName" name="lastName" placeholder="Name" >
        </div>
        <div>
            <label for="email">Email: </label>
            <input [(ngModel)]="model.email" type="text" id="email" name="email" placeholder="Name" >
        </div>
        <div>
            <label for="password">Password: </label>
            <input [(ngModel)]="model.password" type="text" id="password" name="password" placeholder="Name" >
        </div>
        <button type="submit">Submit</button>
    </form>
</div>

2 个答案:

答案 0 :(得分:0)

我不知道您的数据库结构是什么样子,但是可以说它与您的前端相同...

  • 首先我不确定为什么您的userFromDb是一个数组,它会返回多个用户吗?

如果您只想插入值,那么最简单的方法是:

this.userService.getUser(id).subscribe(result => {
  console.log(result)
  this.userFromDb = result
  this.model.firstName = this.userFromDB[0].firstName
  // same with other values here
  console.log(this.userFromDb)
});

答案 1 :(得分:0)

this.userService.getUser(id).subscribe(result => {
  console.log(result);
  this.userFromDb:User = result[0];
  console.log(this.userFromDb);
});

HTML

<div>
    <form action="" #f="ngForm" (ngSubmit)="saveUser()" novalidate>
        <div>
            <label for="firstName">First Name: </label>
            <input [(ngModel)]="userFromDb.firstName" type="text" id="firstName" name="firstName" placeholder="Name">
        </div>
        <div>
            <label for="lastName">Last Name: </label>
            <input [(ngModel)]="model.lastName" type="text" id="lastName" name="lastName" placeholder="Name" >
        </div>
        <div>
            <label for="email">Email: </label>
            <input [(ngModel)]="userFromDb.email" type="text" id="email" name="email" placeholder="Name" >
        </div>
        <div>
            <label for="password">Password: </label>
            <input [(ngModel)]="userFromDb.password" type="text" id="password" name="password" placeholder="Name" >
        </div>
        <button type="submit">Submit</button>
    </form>
</div>