我正在尝试遍历JSON对象并创建mat-form-field输入,其类型根据特定JSON值而变化。我像这样遍历我的对象
<mat-form-field *ngFor="let entry of item.entry" class="form-field" appearance="outline">
<input matInput id={{entry.id}} value={{entry.value}}>
</mat-form-field>
这没问题。但是,当我去检查条目的格式(包含在JSON对象中)时,就像这样...
<mat-form-field *ngFor="let entry of item.entry" class="form-field" appearance="outline">
<input matInput *ngIf="entry.format=='STRING'" id={{entry.id}} value={{entry.value}}>
<input matInput *ngIf="entry.format=='INTEGER'" id={{entry.id}} value={{entry.value}} type="number">
</mat-form-field>
我收到错误:ERROR Error: mat-form-field must contain a MatFormFieldControl.
这对我来说没有意义,请注意,因为matInput永远不会改变。我想念什么吗?
这里也是我正在引用的JSON结构的示例:
{
"group-name":"Core",
"entry":[
{
"id":"foo",
"value":"foo",
"format":"STRING",
"label":"IP Address",
"edit":true,
"tool-tip":"Insert Host IP Address",
"hidden":false
},
{
"id":"bar",
"value":"4200",
"format":"INTEGER",
"label":"Port",
"edit":true,
"tool-tip":"Port for connections",
"hidden":false
},
]
},
有什么想法吗?
错误说明了一切:
mat-form-field
必须包含MatFormFieldControl
换句话说,您的input
必须为“ static”,您不能使用*ngIf
对其进行封装。
您可以解决此问题的方法是这样的:
TS(组件):
readonly inputTypeMapper = {
INTEGER: 'number'
STRING: 'text',
};
HTML(Template):
<mat-form-field *ngFor="let entry of item.entry" class="form-field" appearance="outline">
<input
matInput
[id]="entry.id"
[type]="inputTypeMapper[entry.format]"
[value]="entry.value">
</mat-form-field>
我认为您的错误是在ngFor循环中使用了点号。
ngFor循环的正确用法是:
* ngFor =“让条目进入条目”
因此,您的情况将是:
* ngFor =“条目的标题”
这是因为您要逐个循环浏览条目(作为条目,在您的情况下为e)。然后,当您有循环中的每个条目时-查看一个条目,然后可以使用点符号获取信息。
您使用点表示法来访问对象中的项,就像您对插值所做的正确操作一样:{{entry.id}}您也可以使用属性绑定[value] =“ entry将其传递回ts文件。 .id“
Supporting Documentation from Angular.io祝你好运!变得更加简单。