加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2:模板驱动表单,将对象从选定元素传递到提交对象

发布时间:2020-12-17 17:22:24 所属栏目:安全 来源:网络整理
导读:你好,我是Angular 2的新手,我正在寻找一种解决这个问题的好方法.所以我的用户对象里面包含另一个对象.该用户是一个界面: export interface userModel{ name: string,service: Service} 获得了一系列用于创建新用户的服务和表单. form #f="ngForm" (submit)=
你好,我是Angular 2的新手,我正在寻找一种解决这个问题的好方法.所以我的用户对象里面包含另一个对象.该用户是一个界面:

export interface userModel{
  name: string,service: Service
}

获得了一系列用于创建新用户的服务和表单.

<form #f="ngForm" (submit)="addUser(f.value,f.valid)">
    <label for="name" class="col-sm-1 control-label">Name</label>
    <div class="col-sm-4">
        <input class="form-control" [(ngModel)]="userModel.name" #name="ngModel" name="name" ng-maxlength="49" />
    </div>
    <label class="col-sm-1 control-label">Service</label>
        <select class="form-control" name="service" [(ngModel)]="userModel.service">
            <option *ngFor='let service of services' [value]='service'>{{service.name}}</option>
        </select>
    </div>
    <button class="btn btn-primary" type="submit">Create</button>
</form>

如何将选定的服务对象传递给User对象?当我这样填充它时,我得到:

Object{
  "name": "something","service": "[Object object]"
}

所以显然我不能将对象作为值传递给select元素.
然后我将该值设置为Service的id.
修改界面:

export interface UserModel{
   name: string,serviceId: number
}

在提交之前,我通过服务数组中的id找到Service对象,并将其设置在User对象中,其中包含Service对象.

userModel: UserModel;
user: User;

submit(model: UserModel ){
   this.user = {
     name : model.name,service: this.findService(model.serviceId) 
  }
}



ngOnInti(){
 this.userModel= <userModel>{};
}

这个可以吗 ?有没有更好的方法来管理这个?这是工作示例,只是(手写)代码的一部分.谢谢

解决方法

它存储了[Object object],因为你有value属性可以对对象进行字符串化.由于您希望在选项选择上存储对象值,因此应使用[ngValue]而不是[value].基本上[ngValue]属性仍然存在&保持对象价值快乐.

标记

<select class="form-control" name="service" [(ngModel)]="userModel.service">
  <option *ngFor='let service of services' [ngValue]='service'>
     {{service.name}}
  </option>
</select>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读