2016-11-28 77 views
11

是不是可以在ng内容中有表单输入元素,并且具有“连接”到父组件的ngForm实例?问:如何在ng-content中使用Angular 2模板表单?

拿这个基本模板父组件:

<form (ngSubmit)="onSubmit(editForm)" #editForm="ngForm" novalidate>    
<ng-content></ng-content> 
<button type="submit">Submit</button> 
</form> 

然后子组件,这是把里面“NG-内容”,像这里面:

<input type="text" [(ngModel)]="user.firstName" #firstName="ngModel" name="firstName" required minlength="2"> 

在提交的父窗体,子控件不可用,这也意味着子窗体组件中的任何内容的肮脏/验证不会反映在父窗体上。

这里缺少什么?

+0

我很确定这不起作用。该元素仅显示在子组件中,但仍然是父元素的子元素。 –

+0

@GünterZöchbauer有没有什么方法可以将子输入字段与父组件中的表单(ngForm)联系起来?使用ReactiveForms,我可以填充父FormGroup,并在子组件上使用[formGroup],但使用模板驱动的表单是不可能的? – SondreB

+0

这也适用于模板驱动的表单。有一段时间没有做完。 –

回答

11

在这一点上你有很好的机会提出了另一种解决方案,但我只是想出了一个办法来做到这一点。希望它会帮助你或其他人。

import { NgModel } from '@angular/forms'; 
import { Component, ContentChildren, ViewChild, QueryList, AfterViewInit } from '@angular/core'; 

@Component({ 
    selector: 'my-custom-form', 
    template: ` 
    <form (ngSubmit)="onSubmit(editForm)" #editForm="ngForm" novalidate>    
     <ng-content></ng-content> 
     <button type="submit">Submit</button> 
    </form> 
    `, 
}) 
export class MyCustomFormComponent implements AfterViewInit { 
    @ContentChildren(NgModel) public models: QueryList<NgModel>; 
    @ViewChild(NgForm) public form: NgForm; 

    public ngAfterViewInit(): void { 
    let ngContentModels = this.models.toArray(); 
    ngContentModels.forEach((model) => { 
     this.form.addControl(model); 
    }); 
    } 

    public onSubmit(editForm: any): void { 
    console.log(editForm); 
    } 
} 

然后你就可以在你的模板中使用这样的:

<my-custom-form> 
    <input name="projectedInput" ngModel> 
</my-custom-form> 

当您提交表单,您将看到projectedInput窗体控件添加到NgForm。

注:我只尝试添加来自AfterViewInit生命周期挂钩的投影输入。它可能会提前工作,我不确定。这样做可能还有一些我不知道的问题。因人而异。

+0

如果你也指定'{descendants:true}'给'ContentChildren',那么它也会抓取后代,你不需要输入直接的孩子:) – Carlos

+1

当我写这个答案时,我没有任何用这种方法运气好。我不确定这是一个错误还是什么,但那是我尝试的第一件事。自从Angular 2测试版以来,我还没有尝试过。 – instantaphex

+0

有关上述的任何官方回复或文档? – Jek