这是我的用户模型
export interface User {firstName: string; lastName: string isActive?: boolean; registered?: any; balance?: number; showExtended?: boolean; email?:string; address: { city: string, state: string, zip: string };}
当我们使用angular form ngSubmit函数提交时,city,state和zip不会嵌套到地址对象中。从console.log中,用户对象是
{"firstName":"Kris","lastName":"Mell","email":"mell@gmail.com","city":"Dallas","state":"TX","zip":"00034","balance":200}
我期待用户对象的console.log是这样的。与城市,地址和国家包裹地址和作为用户的子对象。
{"firstName":"Kris","lastName":"Mell","email":"mell@gmail.com", address :{"city":"Dallas","state":"TX","zip":"00034"},"balance":200}
可能出错?
这是表格
<form #userForm="ngForm" (ngSubmit) = "onSubmit(userForm)">
<h2>Add User</h2>
<div class="form-group">
<label>First Name</label>
<input type="text" required minlength="2" class="form-control" [ngClass]="{'is-invalid' : userFirstName.errors && userFirstName.touched, 'is-valid': !userFirstName.errors}"
name="firstName" [(ngModel)]="user.firstName" #userFirstName="ngModel" />
<div class="invalid-feedback" [hidden] = "!userFirstName.errors?.required">
First Name is required
</div>
<div class="invalid-feedback" [hidden] = "!userFirstName.errors?.minlength">
First Name should be atleast 2 characters long
</div>
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" name="lastName" [(ngModel)]="user.lastName" />
</div>
<div class="form-group">
<label>Email</label>
<input type="text" required class="form-control" [class.is-invalid] = "userEmail.errors && userEmail.touched" name="email" #userEmail = "ngModel" [(ngModel)]="user.email" pattern ="^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$"/>
<div class="invalid-feedback" [hidden] = "!userEmail.errors?.required">
Email is required
</div>
<div class="invalid-feedback" [hidden] = "!userEmail.errors?.pattern">
Please enter valid email
</div>
</div>
<div class="form-group">
<label>City</label>
<input type="text" class="form-control" name="city" [(ngModel)]="user.address.city" />
</div>
{{user.address.city}}
<div class="form-group">
<label>State</label>
<input type="text" class="form-control" name="state" [(ngModel)]="user.address.state" />
</div>
<div class="form-group">
<label>Zip</label>
<input type="text" class="form-control" name="zip" [(ngModel)]="user.address.zip" />
</div>
<div class="form-group">
<label>Balance</label>
<input type="number" class="form-control" name="balance" [(ngModel)]="user.balance" />
</div>
<button class="btn btn-block mb-3" [disabled]="userForm.invalid" [ngClass]="currentClasses">Add New User</button>
onSubmit({value, valid}: {value: User , valid: boolean}) {
console.log('form submitted: ' + JSON.stringify(value));
this.users.unshift(value);
this.form.reset();
}
答案 0 :(得分:0)
如果您使用的是模板驱动表单,那么您只需要ngModelGroup
:
<input name='firstName' ngModel>
...
<div ngModelGroup='address'>
<input name='city' ngModel>
...
</div>