2
votes

I'm working with a nested form group structure with Angular 2 beta "FormBuilder" and for the life of me I can't get values into the nested form group. It's weird because binding works just fine. I can send a "user" object to the form and it fills in all the values for the user and their address. But when sending the form value out (say, to an HttpPost), it looks just like the object below...

FWIW I'm following Mosh Hamedani's excellent Angluar 2 course on Udemy and have checked and double checked that the relevant code matches his here: https://github.com/mosh-hamedani/angular2-course

Perhaps what I need is to be told where else to look in my code?

Here's my form group as shown by placing {{ form.value | json }} at the end of my form:

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

this is the constructor in my component:

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: []
            })
        });
    }

This is the form in my template (truncated for brevity):

<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

1 Answers

0
votes
 ng-control="street"

should be

 ngControl="street" 

like you did with name