Angular 2嵌套表单组包含空值

时间:2016-06-11 18:04:44

标签: angularjs typescript angular angular2-forms angular2-formbuilder

我正在使用Angular 2 beta“FormBuilder”的嵌套表单组结构,对于我的生活,我无法将值输入到嵌套表单组中。这很奇怪,因为绑定工作得很好。我可以向表单发送“用户”对象,它会填写用户及其地址的所有值。但是当发送表单值(例如,发送给HttpPost)时,它看起来就像下面的对象...

FWIW我正在跟随Mosh Hamedani在Udemy上的优秀Angluar 2课程并检查并仔细检查相关代码是否与他的匹配:https://github.com/mosh-hamedani/angular2-course

也许我需要知道在我的代码中还有哪些内容?

这是我的表单组,如放置{{form.value | json}}在我的表格末尾:

{
 "name": "Leanne Graham",
 "email": "Sincere@april.biz",
 "phone": "1-770-736-8031 x56442",
 "address": {
    "street": null,
    "suite": null,
    "city": null,
    "zipcode": null
   }
}

这是我组件中的构造函数:

constructor(
        fb: FormBuilder, 
        private router: Router, 
        private usersService: UsersService,
        private params: RouteParams
    ){
        this.form = fb.group({
            name: ['', Validators.required],
            email: ['', EmailValidators.mustBeEmail], // I hadn't considered the obvious: if it doesn't exist it also doesn't qualify as email.
            phone: [],
            address: fb.group({
                street: [],
                suite: [],
                city: [],
                zipcode: []
            })
        });
    }

这是我模板中的表单(为简洁而截断):

<div class="col-md-6 well">
        <!--the "fieldset" element is needed for this kind of grouped layout.-->
        <form [ngFormModel]="form" (ngSubmit)="save()">
            <fieldset>
                <legend>User</legend>
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" [(ngModel)]="user.name" ngControl="name" #name="ngForm" class="form-control">
                    <div class="alert alert-danger" *ngIf="name.errors && name.touched">
                        The user name is required.
                    </div>
                </div>
                *** Email and Phone similar ***
            </fieldset>
            <fieldset ngControlGroup="address">
                <legend>Address</legend>
                <div class="form-group">
                    <label>Street</label>
                    <input type="text" [(ngModel)]="user.address.street" ng-control="street" class="form-control">
                </div>
                *** suite, city, and zip similar ***
            </fieldset>
            {{ form.value | json }}
            <button [disabled]="!form.valid" class="btn btn-primary" type="submit">Save</button>
        </form>
    </div>

1 个答案:

答案 0 :(得分:0)

 ng-control="street"

应该是

 ngControl="street" 

就像你对name

所做的那样