【问题标题】:Angular error: If ngModel is used within a form tag, either the name attribute must be set or [duplicate]角度错误:如果在表单标记中使用 ngModel,则必须设置名称属性或 [重复]
【发布时间】:2018-02-03 19:31:56
【问题描述】:

关于错误有很多类似的问答:如果在表单标签中使用了ngModel,要么必须设置name属性,要么必须在ngModelOptions中将表单控件定义为'standalone'。 解决方案是按照消息中的描述定义 name 属性。但这对我不起作用。我的 app.component.html 中有下一个标记:

<form id="form1" name="form1" #form="ngForm">
  <div class="form-group">
    <input id="input1" name="input1" [(ngModel)]="metaScript" />
    ...

我仍然在 app.component.html 第 3 行出现错误:如果在表单标签中使用 ngModel,则必须设置 name 属性或者...

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    发生此错误是因为在下面的 html 标记中还有一行没有 name 属性。

    <form id="form1" name="form1" #form="ngForm">
      <div class="form-group">
        <input id="input1" name="input1" [(ngModel)]="metaScript" />
        ... 
        <input id="input2" [(ngModel)]="metaScriptMessage"/>
      </div>
    </form>
    

    但是浏览器还是报第一行有错误。如果您在这两者之间有其他元素,则很难发现错误的根源。

    【讨论】:

      【解决方案2】:

      首先请将 FormsModule 注入你的 app.module.ts

      import { FormsModule }   from '@angular/forms';
      @NgModule({
        imports: [
          FormsModule,
          .......
        ]
      })
      

      现在在您的模板 app.component.html 文件中

      <form id="form1" name="form1" #form="ngForm">
        <div class="form-group">
          <input type="text" id="input1" name="input1" [(ngModel)]="metaScript" />
          ...
      

      注意:要求您像上面一样在输入元素中输入 type="text"

      【讨论】:

        猜你喜欢
        • 2017-01-11
        • 2018-10-05
        • 2019-05-04
        • 2019-05-24
        • 1970-01-01
        • 1970-01-01
        • 2018-04-14
        • 2016-08-10
        • 2012-03-13
        相关资源
        最近更新 更多