2016-11-28 78 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