问:如何使用带有 ng-content 的 Angular 2 模板表单? [英] Q: How to use Angular 2 template form with ng-content?

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

问题描述

是否不可能在 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 生命周期挂钩的投影输入.它可能更早工作,我不确定.这样做也可能存在一些我不知道的问题.天啊.

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.

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

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