问:如何将Angular 2模板形式与ng-content一起使用? [英] Q: How to use Angular 2 template form with ng-content?

查看:89
本文介绍了问:如何将Angular 2模板形式与ng-content一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否不可能在ng-content内包含表单输入元素,并使该连接"到父组件的ngForm实例?

Is it not possible to have form input elements within an ng-content and have that "connect" to the ngForm instance of the parent component?

使用此基本模板作为父组件:

Take this basic template for a parent component:

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

然后将子组件放入"ng-content"中,如下所示:

Then inside the child component, which is put inside "ng-content", something like this:

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

在提交父表单时,子控件不可用,这也意味着子组件中任何内容的脏/验证都不会反映在父表单上.

On submit of the parent form, the child controls are not available, which also means that dirty/validation of whatever is in the child component is not reflected on the parent form.

这里缺少什么?

推荐答案

目前您很有可能提出了另一种解决方案,但我只是想出了一种方法来解决.希望它将对您或其他人有所帮助.

There is a good chance that you have come up with another solution at this point but I just figured out a way to do this. Hopefully it will help you or someone else.

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);
  }
}

然后您可以像这样在模板中使用它:

Then you can use it in your template like this:

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

提交表单时,您将看到projectedInput表单控件已添加到NgForm.

When you submit the form, you will see that the projectedInput form control is added to the NgForm.

注意::我仅尝试从AfterViewInit生命周期挂钩添加预计的输入.我不确定它可能会更早工作.这样做可能还会有一些我不知道的问题. YMMV.

Note: I only tried adding the projected inputs from the AfterViewInit lifecycle hook. It may work earlier, I'm not sure. There also may be some issues with doing this that I'm not aware of. YMMV.

这篇关于问:如何将Angular 2模板形式与ng-content一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆