Angular2和ngIf

时间:2017-08-22 20:32:24

标签: angular validation

以下Angular 2(版本4.3.5)代码无法按预期工作。

<link 
    rel="stylesheet" 
    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" 
    integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ"
    crossorigin="anonymous">   
<script 
    src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" 
    integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn"
    crossorigin="anonymous">
</script>
<form style="margin:50px;">
    <div class="form-control">
        <label for="firstName">First Name</label>
        <input 
            ngControl="firstName" 
            id="firstName" 
            #firstName 
            type='text' 
            class='form-control' 
            required>
        <div 
            class="alert alert-danger" 
            *ngIf="!firstName.valid && firstName.touched">
                A first name is required
        </div>
    </div>
    <br/>
    <button class="btn btn-primary" type="submit">
        Submit!
    </button>
</form>

ngIf声明

*ngIf="!firstName.valid"

页面加载时会显示错误消息div,并且在输入文本后仍然可见。

ngIf语句如上所述

*ngIf="!firstName.valid && firstName.touched"

错误消息未显示。

我错过了什么? 谢谢A.G。

2 个答案:

答案 0 :(得分:0)

我认为你需要通过输入=&#34; ngControl&#34;来指定#所指的模板变量的类型。或=&#34; ngModel&#34;

<input ngControl="firstName" 
        id="firstName" 
        #firstName="ngForm"   // or ngModel if you're using 2-way binding
        type='text' 
        class='form-control' 
        required>
    <div 
        class="alert alert-danger" 
        *ngIf="!firstName.valid && firstName.touched">
            A first name is required
    </div>

见这里:Angular2 Forms :Validations, ngControl, ngModel etc

答案 1 :(得分:0)

添加了一个与firstName和comment属性联系的类 在app.module.ts中导入FormsModule 将Contact的类型和初始化模型添加到ContactFormComponent类型

<form #contactForm='ngForm' style='margin:50px;'>
    <div class='form-group'>
        <label for='firstName'>First Name</label>
        <br />
        <input id='firstName' type='text' class='form-control' [(ngModel)]='model.firstName' required name='firstName' #firstName="ngModel"
            (change)='onChange(ngModel)'>
        <div [hidden]="firstName.valid || firstName.pristine" class="alert alert-danger">
            A first name is required.
        </div>
    </div>
    <div class='form-group'>
        <label for='comment'>Comment</label>
        <br />
        <textarea id='comment' class='form-control' [(ngModel)]='model.comment' required name='comment' #comment="ngModel" ></textarea>
        <div [hidden]="comment.valid || comment.pristine" class="alert alert-danger">
            A comment is required.
        </div>
    </div>
    <button class='btn btn-primary' type='submit'>
         Submit
    </button>
</form>

https://angular.io/guide/forms后面的示例之后进行了更改,现在组件按预期工作。