【问题标题】:My nested Angular reactive form is not getting the FormGroup from the parent component我的嵌套 Angular 反应式表单没有从父组件获取 FormGroup
【发布时间】:2018-08-06 06:34:56
【问题描述】:

我在 YouTube 上的 AngularConnect 2017 上看到了 Kara Erickson 的 Angular 表单演示。我特别感兴趣的部分是where she describes nested reactive forms

我已经按照 Kara 的描述做了所有事情,但无论我尝试什么,我最终都会得到一个 null parentForm。

我在下面复制了我的代码的简化版本。问题是在child-form 组件中我得到null

// 父组件

@Component({
  selector: 'parent-form',
  styleUrls: ['./parent-form.component.css'],
  template: `
    <form [formGroup]="createAlbumProfileForm" (ngSubmit)="onFormSubmitted($event)">
        <input type="text" placeholder="Something unique to parent form"/>
        <child-form></child-form>
    </form>
  `
})
export class ParentFormComponent implements OnInit {

  parentForm: FormGroup;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.parentForm = this.formBuilder.group({
      yoloField: this.formBuilder.control('')
    });
  }

// 子组件

@Component({
    selector: 'child-form',
    styleUrls: [ './child-form.component.scss' ],
    viewProviders:[ { provide: ControlContainer, useExisting: FormGroupDirective } ],
    template: `
      <div formGroupName="songName" class="form-group"></div
    `
})
export class ChildFormComponent implements OnInit {
    childForm: FormGroup;

    constructor(private parentForm: FormGroupDirective) {
        this.childForm = parentForm.form; // null
    }
}

【问题讨论】:

  • 组件的生命周期似乎有问题:在视频中 formGroup 在父组件的构造函数中初始化,但在您的示例中,您将其初始化为 OnInit。问题是孩子的构造函数在父母的 OnInit 之前被调用,这就是你得到 null 的原因。
  • 您的子组件应该从"@angular/forms" 实现ControlValueAccessor 接口,这样您的父组件就可以将formcontrolname 分配给他的子组件
  • @Yevgeniy.Chernobrivets 宾果游戏!这是造成问题的原因,谢谢!
  • @Ricardo 你有一个例子来描述你的意思吗?我不明白

标签: angular angular2-forms nested-forms angular-reactive-forms


【解决方案1】:

我遇到了同样的问题,实际上在构造函数中同时初始化两种表单是行不通的。它确实要么在 ngOnInit 中同时拥有,要么在构造函数中拥有父 init,在 ngOnInit 中拥有子 init。

那么最好把所有东西都放在ngOnInit中,否则再多一层嵌套就不行了。

所以:

父组件:

@Component({
  //...
})
export class ParentFormComponent implements OnInit {

  // ...

  ngOnInit() {
    this.parentForm = this.formBuilder.group({});
  }

儿童组件:

@Component({
    // ...
})
export class ChildFormComponent implements OnInit {
    childForm: FormGroup;

    constructor(private parent: FormGroupDirective) {
    }

    ngOnInit() {
        this.childForm = new FormGroup(/*....*/);
        this.parentForm.form.addControl('childData', this.childForm);
    }
}

【讨论】:

  • 我所说的“两个初始化”是代码 1)在 OP 问题的父组件中的 ngOnInit 和 2)在 OP 问题的子构造函数中。希望这更清楚。
【解决方案2】:

这似乎是组件生命周期的问题:在视频中 FormGroup 在父组件的构造函数中初始化,但在您的示例中,您将其初始化为 OnInit。问题是孩子的构造函数在父母的 OnInit 之前被调用,这就是你得到 null 的原因。

【讨论】:

  • 您已经给出了原因 - 您能否也描述一个解决方案?谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-04
  • 1970-01-01
  • 2021-07-07
  • 1970-01-01
  • 1970-01-01
  • 2019-03-27
  • 2017-07-20
相关资源
最近更新 更多