【问题标题】:Angular: MatFormFieldControl Error when using ngIf and iterationAngular:使用 ngIf 和迭代时出现 MatFormFieldControl 错误
【发布时间】:2020-02-12 20:41:08
【问题描述】:

我正在尝试遍历 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
        },
     ]
  },

有什么想法吗?

【问题讨论】:

    标签: angular angular-material2 angular-forms


    【解决方案1】:

    错误不言自明:

    mat-form-field 必须包含一个 MatFormFieldControl

    换句话说,就是说你的input必须是“static”,你不能有一个*ngIf来封装它。


    您可以做些什么来解决您的问题:

    TS(组件)

    readonly inputTypeMapper = {
      INTEGER: 'number'
      STRING: 'text',
    };
    

    HTML(模板)

    <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>
    

    【讨论】:

      【解决方案2】:

      我认为您的错误是在 ngFor 循环中使用点符号。

      ngFor循环的正确用法是:

      *ngFor="let entry of entries"
      

      所以在你的情况下,它会是:

      *ngFor="let e of entries"
      

      这是因为您希望单独循环遍历条目(作为条目,在您的情况下为 e)。然后,当您在循环中有每个条目时 - 查看一个条目,您就可以使用点符号获取信息。

      您使用点符号来访问对象中的项目,正如您为插值所做的那样:{{ entry.id }}

      您可以使用属性绑定 [value]="entry.id" 将 ID 传回 ts 文件

      Supporting Documentation from Angular.io 祝你好运!它变得更容易了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-27
        • 2016-09-13
        • 2021-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-17
        相关资源
        最近更新 更多