角度嵌套模板驱动表单

时间:2018-03-14 12:27:31

标签: angular angular-forms

我尝试使用嵌套模板驱动表单,但我PostEditorComponent textarea中的ngModel无法找到ngForm中的ModalFormComponent。这是我目前的设置:

Component({
    selector: 'modal-form',
    template: `
        <div class="modal-window">
            <div class="modal-body">
                <form #form="ngForm">
                    <ng-content></ng-content>
                </form>
            </div>
        </div>
    `
})
export class ModalFormComponent {
}

@Component({
    selector: 'post-editor',
    template: `
        <textarea [(ngModel)]="postContent" required name="postContent"></textarea>
    `
})
export class PostEditorComponent {
    public postContent: string;
}

@Component({
    selector: 'write-post',
    template: `
        <modal-form>
            <label>
                Post type: <input type="text" [(ngModel)]="postTitle" name="postTitle"/>
            </label>
            <post-editor></post-editor>
        </modal-form>
    `
})
export class WritePostComponent {
    public postTitle: string;
}

如果我尝试在viewProviders: [{provide: ControlContainer, useExisting: NgForm}] Angular throws中PostEditorComponent使用NullInjectorError: No provider for NgForm!

使用@ViewChildren(NgModel)ngForm.addControl(model)进行手动关联可能是一种解决方案,但由于我必须管理引用,处理AfterViewInitOnDestroy等,因此容易出错。< / p>

关于如何将表单实例注入PostEditorComponent视图的任何想法?

0 个答案:

没有答案