gpt4 book ai didi

angular - 无法读取 null 的属性 'addControl'

转载 作者:行者123 更新时间:2023-12-03 16:24:51 27 4
gpt4 key购买 nike

嵌套表单,尝试在其他表单中添加一个表单,但出现错误“无法读取 null 的属性 'addControl'”。 FormGroupDirective 似乎没有返回父“表单”。尝试应用子表单方法进行嵌套。

    <p>
sub-forms-approach works!
</p>
<form [formGroup]="form">
<!--<input formControlName="name">-->
<app-sub-forms-approach-child-one></app-sub-forms-approach-child-one>

</form>
state: {{form.status}}
data: {{ form.value | json}}

父组件
    import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from
'@angular/forms';

@Component({
selector: 'app-sub-forms-approach',
templateUrl: './sub-forms-approach.component.html',
styleUrls: ['./sub-forms-approach.component.css']
})
export class SubFormsApproachComponent implements OnInit {
form= new FormGroup({

});
constructor() {
}
ngOnInit() {
}

}

子表单 HTML

sub-forms-approach-child-one 有效!

    <div formGroupName='address'>
<input formControlName="pin">
<input formControlName="street">
</div>

子窗体组件
    import { Component, OnInit } from '@angular/core';
import { ControlContainer, FormGroupDirective, FormControl, FormGroup}
from '@angular/forms';
@Component({
selector: 'app-sub-forms-approach-child-one',
templateUrl: './sub-forms-approach-child-one.component.html',
styleUrls: ['./sub-forms-approach-child-one.component.css'],
viewProviders: [
{provide: ControlContainer,
useExisting: FormGroupDirective
}
]
})
export class SubFormsApproachChildOneComponent implements OnInit {
form;
constructor(parent: FormGroupDirective) {
this.form = parent.form;
console.log(parent.form);
}

ngOnInit() {
this.form.addControl('address', new FormGroup({
pin: new FormControl(),
street: new FormControl()
}))
}

}

最佳答案

您无法获取 FormGroupDirective.form在构造函数中,因为 @Input form属性尚未初始化。 Angular 首先在节点创建期间实例化组件类,然后才初始化输入属性。

因此,将您的代码移至 ngOnInit钩:

constructor(private parent: FormGroupDirective) {}

ngOnInit() {
this.form = this.parent.form;
this.form.addControl('address', new FormGroup({
pin: new FormControl(),
street: new FormControl()
}))
}

Ng-run Example

关于angular - 无法读取 null 的属性 'addControl',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49969472/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com