【发布时间】: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
【问题讨论】:
-
你为什么不使用 ReactiveForms?
-
[(ngModel)]="courseName"
-
您是否在 app.module.ts 文件中导入了“FormsModule”?
标签: javascript angular