跨不同组件嵌套的多个 NgModelGroup

Multiple NgModelGroup nesting across different components

当我尝试将 NgModelGroup 嵌套在另一个 NgModelGroup 中时,看起来 Angular 只是忽略它。我正在使用 Angular 12 和模板驱动的表单。

我的代码是这样的:

app.component.html

<form #form="ngForm">
  <div class="col-auto">
    <input name="name" id="name" ngModel /><br />
    <app-address></app-address>
  </div>
  <div class="btn-toolbar">
    <button type="submit" (click)="submit(form)">Submit</button>
  </div>
  <p>{{ form.value | json }}</p>
</form>

address.component.html

<div ngModelGroup="address">
  <input name="street" id="street" ngModel />
  <app-contact></app-contact>
</div>

contact.component.html

<div ngModelGroup="contact">
  <input name="phone" id="phone" ngModel />
</div>

这是实际结果:

{
   "name":"John Snow",
   "address":{
      "street":"201 Somewhere Place, 12"
   },
   "contact":{
      "phone":"6405106300"
   }
}

这就是我试图取得成功的原因:

{
   "name":"John Snow",
   "address":{
      "street":"201 Somewhere Place, 12",
      "contact":{
         "phone":"6405106300"
      }
   }
}

此外,您可以在此处查看代码:https://stackblitz.com/edit/angular-ivy-osf83a?

将我的 Contact typescript 文件中的 NgForm 更改为 NgModelGroup 后问题已解决。

import { Component, OnInit } from '@angular/core';
import { ControlContainer, NgModelGroup } from '@angular/forms';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css'],
  viewProviders: [{ provide: ControlContainer, useExisting: NgModelGroup }],
})
export class ContactComponent implements OnInit {
  constructor() {}

  ngOnInit() {}
}

这是以前的样子。请注意,我只需要更改两个地方:

import { Component, OnInit } from '@angular/core';
import { ControlContainer, NgForm } from '@angular/forms';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css'],
  viewProviders: [{ provide: ControlContainer, useExisting: NgForm }],
})
export class ContactComponent implements OnInit {
  constructor() {}

  ngOnInit() {}
}