将FormGroup作为输入指令传递给子组件,但在父组件中设置subscribe

时间:2017-06-04 19:48:13

标签: angular typescript

好的,我正用这个把头发拉出来。

我有我的父组件:

import { Component, OnInit } from '@angular/core';
import { Guest } from "../models/guest.interface";
import { GuestService } from "../services/guest.service";
import { ActivatedRoute } from "@angular/router";
import { FormControl, FormGroup, FormArray } from '@angular/forms';

import 'rxjs/add/operator/switchMap';
import { GuestFormMapper } from "app/guests/services/guest-form.mapper";

@Component({
    template: `    
        <h1>Guest Viewer</h1>  

        <form [formGroup]="form" novalidate>
            <guest-detail [parent]="form"></guest-detail>
        </form>
`
})
export class GuestViewerComponent implements OnInit {
    form: FormGroup;
    guest: Guest;

    constructor(private guestService: GuestService,
        private route: ActivatedRoute,
        private guestFormMapper: GuestFormMapper) { }

    ngOnInit(): void {
        let id = this.route.snapshot.params['id'];

        if (id) {
            this.route.params
                .switchMap((data: Guest) => this.guestService.get(data.id))
                .subscribe((guest: Guest) => {
                    if (guest) {
                        this.form = this.guestFormMapper.mapToForm(guest);
                    } else {
                        //todo
                    }
                });
        } else {
            this.form = this.guestFormMapper.mapToForm(new Guest());
        }
    }
}

我有以下形式:FormGroup但是在我点击api之前它没有给出值。

我遇到的问题是,在我的孩子组件中,我得到:

ERROR Error: Uncaught (in promise): Error: formGroup expects a FormGroup instance. Please pass one in.

我的孩子组件目前非常简单:

import { Component, Input } from '@angular/core';
import { Guest } from "../models/guest.interface";
import {FormControl, FormGroup, FormArray} from '@angular/forms';

@Component({
    selector: 'guest-detail',
    templateUrl:'guest-detail.component.html',
})
export class GuestDetailComponent {
    @Input()
    parent: FormGroup;
}

然后是html:

<div class="panel-body" [formGroup]="parent">
    <div formGroupName="guest">
        <div class="form-group col-md-3 col-sm-6">
            <label>First Name*  </label>
            <input formControlName="firstname" type="text" class="form-control input-sm">
        </div>
    </div>
</div>

实现这一目标的最佳方法是什么?

我需要重新使用来宾详细信息表格作为其他表格的一部分向前推进,因此将其拆分出来。

0 个答案:

没有答案