且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

形式中形式.表单控件可以继承吗?

更新时间:2023-10-12 16:07:52

更新:

确实有更简单的方法:

import { FormsModule, ControlContainer, NgForm, NgModel } from '@angular/forms';

@Component({
  ...
  viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})
export class ChildComponent {}

另见

以前的版本:

我会说这是可能的.例如,您可以将以下代码添加到您的

I would say it's possible. For example you could add the following code to your

child.component.ts

import { NgForm, NgModel } from '@angular/forms';

@Component({
  selector: 'child-component',
  template: `
      <input type="text" name="thirdControl" [(ngModel)]="thirdControl" />
      <input type="text" name="fourthControl" [(ngModel)]="fourthControl" />
    `
})
export class ChildComponent {
  @ViewChildren(NgModel) ngModels: QueryList<NgModel>;

  constructor(@Optional() private ngForm: NgForm) {}

  ngAfterViewInit() {
    if (this.ngForm) {
      this.ngModels.forEach(model => this.ngForm.addControl(model));
    }
  }
}

Plunker 示例

Angular DI 系统让我们有机会获得对父 NgForm 实例的引用,因为 Angular 依赖解析算法从当前节点开始,并通过元素树向上.在我的例子中,我们可以想象下面的树

Angular DI system gives us the opportunity to get reference to parent NgForm instance because angular dependency resolution algorithm starts with current node and goes up through tree of elements. In my example we can imagine the follwing tree

              @NgModule providers
                    |
                  my-app
                    |
                   form
          /         |       \
   input[text] input[text] child-component

因此,当我们需要 NgForm 令牌时,angular 会按照下一个顺序进行搜索

So when we are requiring NgForm token angular will search it in the next order

child-component
     ||
     \/
    form
     ||
     \/
   my-app
     ||
     \/
  @NgModule

在表单元素上放置 NgForm 指令,以便何时可以获取它.我们还可以获取在 providers 数组中的 NgForm 指令上声明的任何标记.并且这个规则适用于任何节点.

On form element NgForm directive is placed so when can get it. Also we can get any token that was declared on NgForm directive within providers array. And this rule applies to any node.

另见 Angular 2 -ng-bootstrap 如何为它们的 NgbRadio 指令提供 NgbRadioGroup 和 NgbButtonLabel?

然后我只是将子 NgModel 指令手动添加到 NgForm 以便它们应该一起工作.

Then i just added child NgModel directives manually to NgForm so they should work together.