作者:童T-Aurora | 来源:互联网 | 2023-07-12 18:06
data-table.html (parent component)
这是父组件,我将在其中使用一些通用组件,并且我想将该组件绑定到反应形式。
```->
开始编辑以查看发生了一些魔术:)
```
custom-dropdown.component.html (child component)
这是通用组件,其中我从父组件获取formGroup和formControl并将其绑定到模板,如建议的
```
``
custom-dropdown.component.ts
```
import { Component,OnInit,Input } from "@angular/core";
@Component({
selector: "app-custom-dropdown",templateUrl: "./custom-dropdown.component.html",styleUrls: ["./custom-dropdown.component.scss"]
})
export class CustomDropdownComponent implements OnInit {
constructor() {}
@Input() fieldControlName;
@Input() fieldIndex;
@Input() fieldFormGroup;
cities = [
{ id: 1,name: "Hydrogen" },{ id: 2,name: "Helium" },{ id: 3,name: "Pavilnys",disabled: true },{ id: 4,name: "Lithium" },{ id: 5,name: "Oxygen" }
];
ngOnInit() {
console.log(this.fieldControlName);
console.log(this.fieldIndex);
}
}
```
when i am trying to execute this code i am getting the below error
**ERROR Error: Cannot find control with name: 'fieldControlName'
at _throwError (forms.js:3357)
at setUpControl (forms.js:3181)
at FormGroupDirective.addControl (forms.js:7345)
at FormControlName._setUpControl (forms.js:8070)
at FormControlName.ngOnChanges (forms.js:7993)
at checkAndUpdateDirectiveInline (core.js:31906)
at checkAndUpdateNodeInline (core.js:44367)
at checkAndUpdateNode (core.js:44306)
at debugCheckAndUpdateNode (core.js:45328)
at debugCheckDirectivesFn (core.js:45271)
**
Please help me in which part i am doing mistakes here..
您需要更改模板以使其成为属性绑定表达式,而不是字符串值分配:
formCOntrolName="fieldControlName"
这将分配给formControlName
属性"fieldControlName"
字符串文字。
[formControlName]="fieldControlName"
会将formControlName
属性绑定到fieldControlName
属性。
编辑:
修复模板中的formControlName
绑定。您只需要传递controlName就足以使其正常工作。
[fieldFormGroup]="userForm">
这一次,我们将使用字符串分配代替属性绑定。您无需显式地找到绑定它的确切控件。
上面的行已经指定了formGroupName
。因此,此组件的子代将知道它属于哪个formGroum。