问:如何使用Angular 2模板表单和ng内容?
是否不可能在ng内容中包含表单输入元素并将其“连接”到父组件的ngForm实例 将此基本模板作为父组件:问:如何使用Angular 2模板表单和ng内容?,angular,angular2-forms,Angular,Angular2 Forms,是否不可能在ng内容中包含表单输入元素并将其“连接”到父组件的ngForm实例 将此基本模板作为父组件: <form (ngSubmit)="onSubmit(editForm)" #editForm="ngForm" novalidate> <ng-content></ng-content> <button type="submit">Submit</button> </form> 提交
<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">
<my-custom-form>
<input name="projectedInput" ngModel>
</my-custom-form>
提交父窗体时,子控件不可用,这也意味着子组件中任何内容的脏/验证都不会反映在父窗体上
这里缺少了什么?在这一点上,您很有可能想出了另一种解决方案,但我刚刚找到了一种方法。希望它能帮助你或其他人
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);
}
}
从'@angular/forms'导入{NgModel};
从“@angular/core”导入{Component,ContentChildren,ViewChild,QueryList,AfterViewInit};
@组成部分({
选择器:“我的自定义表单”,
模板:`
提交
`,
})
导出类MyCustomFormComponent在ViewInit之后实现{
@ContentChildren(NgModel)公共模型:QueryList;
@ViewChild(NgForm)公共表单:NgForm;
public ngAfterViewInit():void{
让ngContentModels=this.models.toArray();
ngContentModels.forEach((模型)=>{
this.form.addControl(model);
});
}
public onSubmit(editForm:any):无效{
控制台日志(editForm);
}
}
然后,您可以在模板中使用它,如下所示:
<input type="text" [(ngModel)]="user.firstName" #firstName="ngModel" name="firstName" required minlength="2">
<my-custom-form>
<input name="projectedInput" ngModel>
</my-custom-form>
提交表单时,您将看到projectedInput表单控件已添加到NgForm中
注意:我只尝试添加来自AfterViewInit生命周期挂钩的投影输入。我不确定它可能会更早起作用。这样做也可能有一些我不知道的问题。YMMV.我很确定这不会奏效。元素仅显示在子组件中,但它仍然是父元素的子元素。@GünterZöchbauer是否有办法将子输入字段与父组件中的表单(ngForm)连接起来?使用ReactiveForms,我可以填充父FormGroup,并在子组件上使用[FormGroup],但不可能使用模板驱动的表单?这也适用于模板驱动的表单。已经有一段时间没有了。如果您也将
{substands:true}
指定给ContentChildren
,那么它也将获取子体,您不需要将输入作为直接子体:)当我写这个答案时,我对这种方法没有任何运气。我不确定这是一个bug还是什么,但这是我尝试的第一件事。自从Angular 2 beta后期以来,我就没有尝试过。在我提交表单(内容投影)重新加载页面时,是否有关于上述内容的官方响应或文档?@instantaphex。stackblitz:@danielgi确保在表单中添加(ngSubmit)处理程序。还要确保从@angular/forms导入FormsModule。我已经把你的stackblitz项目交给了大家演示?