在這一點上你有很好的機會提出了另一種解決方案,但我只是想出了一個辦法來做到這一點。希望它會幫助你或其他人。
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
這也適用於模板驅動的表單。有一段時間沒有做完。 –