Angular(无法读取 null 的属性(读取 'addControl') - 更改子组件中的表单值



我想从子组件更新表单值。下面是父组件:

app.component.ts

ngOnInit() {
this.form = this.fb.group({
priority: [this.editPriority, Validators.nullValidator],
. 
.
.
});
}

app.component.html

<div *ngIf="editType === 'priority'">
<app-child[form]="form"></app-child>
</div>

child.component.ts:

export class ChildComponent implements OnInit {
@Input() form: FormGroup;
constructor() { }
ngOnInit(): void {
}
}

child.component.html:

<div class="col-sm-2">
<label for="priority"> Priority</label>
</div>
<div class="input-group col-sm-10">
<input type="text" class="form-control" id="priority" name="priority" formControlName="priority"
placeholder="priority">
</div>

我尝试像这个stackBlitz,但我得到了以下错误:

TypeError: Cannot read properties of null (reading 'addControl')

我试着添加:

this.form.addControl('priority', new FormControl());

ngOnInit中,但我仍然得到了错误。

对于通过子组件更新数据有什么建议吗?

法赞。我用角事件发射器,孩子调用一个函数在父(或者相反)。此函数存在于父类或子类中,并在需要时调用,包括传递参数的能力。我不确定它是否适合你的情况,但我知道它经常对我很有效。

下面是一个简单的例子:将Event从子组件传递给父组件

最新更新