【问题标题】:how do I implement template variables in angular?如何以角度实现模板变量?
【发布时间】:2020-03-08 19:49:34
【问题描述】:

我正在尝试提取 ngModel 对象以进行表单验证,但在提供服务时,我的模板变量出现错误。

代码如下:

<form>
    <div class="form-group">
        <label for="courseName">Course Name</label>
        <br />
        <input type="text" id="courseName" ngModel name="courseName" #courseName="ngModel" required />
        <br />
        <div *ngIf="!courseName.valid" class="alert alert-danger">field is required</div>
        <label for="category">Category</label>
        <br />
        <select name="category" id="category" class="form-control-lg" ngModel>
            <option value="test">poop</option>
        </select>
        <div class="checkbox">
            <label for="checkbox">
                <input id="checkbox" type="checkbox" name="moneyBack" />30-day money back guarantee
            </label>
        </div>
    </div>
    <button class="btn btn-primary">Submit</button>
</form>

编辑
经过测试,我发现在分配模板变量时出现问题,并且我注意到我的代码编辑器中的“#”符号与我正在观看的教程颜色不同,这意味着编辑器不是识别语法,因此该语法可能已被弃用(这是可能的,我正在遵循的教程似乎有点旧)或者我执行错误,声明模板变量的正确方法是什么?

或者更重要的是哈哈

访问表单控件对象的正确方法是什么,以便我可以获得 .value、.pristine、.touched 属性?

<#templateVariable ngModel name="test"> **No Error**
<#templateVariable="ngModel" ngModel name="test>**ERROR**

编辑

编辑
问题在于命名 ngModel 和字段相同
编辑

here is a screenshot of the error
here is a screenshot of the import of ngModel

【问题讨论】:

标签: javascript angular


【解决方案1】:

这样使用

[(ngModel)]="courseName"

【讨论】:

  • 别忘了也导入FormModule
【解决方案2】:

您可以检查的事项很少:

  1. 在 app.module.ts 文件中导入 FormModule

  2. 按以下方式更改您的代码

    <input type="text" id="courseName"  [(ngModel)] = "courseName" name="courseName" #course="ngModel" required/>
    
  3. [(ngModel)] 和引用名称必须不同。如果您将两个相同的名称放在“courseName”中,您将收到参考错误!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-15
    • 2019-10-30
    • 2023-03-10
    • 2020-07-18
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多