在这一点上你有很好的机会提出了另一种解决方案,但我只是想出了一个办法来做到这一点。希望它会帮助你或其他人。
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生命周期挂钩的投影输入。它可能会提前工作,我不确定。这样做可能还有一些我不知道的问题。因人而异。
我很确定这不起作用。该元素仅显示在子组件中,但仍然是父元素的子元素。 –
@GünterZöchbauer有没有什么方法可以将子输入字段与父组件中的表单(ngForm)联系起来?使用ReactiveForms,我可以填充父FormGroup,并在子组件上使用[formGroup],但使用模板驱动的表单是不可能的? – SondreB
这也适用于模板驱动的表单。有一段时间没有做完。 –