typescript 在 Angular 2 中,当我尝试使用双向绑定时,ngIF 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38693689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:42:29  来源:igfitidea点击:

In Angular 2, ngIF is not working when i am trying with two way binding

angularjstypescriptangularangular2-templateangular2-forms

提问by Sasi Dhivya

I am working with Angular2with two way binding concept [(ngModel)].I have form with my page and I have to validate the pristine state of the element. So for validation I have used ngIfto check the pristine state of the element. But the condition is not working. I need to check the pristine state for every model change. Below is my app.component.htmlpage:

我正在使用Angular2双向绑定概念[(ngModel)]。我的页面有表单,我必须验证元素的原始状态。所以为了验证,我曾经ngIf检查过元素的原始状态。但条件不起作用。我需要检查每个模型更改的原始状态。下面是我的app.component.html页面:

 <form (ngSubmit)="angular2form(myAngular2Form.employeeDob)" [ngFormModel]="myAngular2Form">

 <input type="text" class="form-control" id="employee" name="employee" [(ngModel)]="employeeDob" required  />            
  <div *ngIf="employeeDob.pristine">
    <p>Please enter the date</p>
 </div>
 <button type="submit" class="btn btn-primary">Register</button>

</form>

This is my component:

这是我的组件:

 export class AppComponent {

employeeDob: String;

  constructor(private myform: FormBuilder) {
    this.employeeDob = '';
 }
 angular2form(date) {
     alert("date submitted successfully");
 }
 }

Thanks for any suggestion

感谢您的任何建议

采纳答案by Günter Z?chbauer

pristineis a property of the Controlnot of the value.

pristine是 的Controlnot 的属性value

You might want to use

你可能想用

<input #employeeDobCtrl="ngForm" type="text" class="form-control" id="employee" name="employee" [(ngModel)]="employeeDob" required  />        
<div *ngIf="employeeDobCtrl.pristine">    

(for the old forms module)

(对于旧的表单模块)

回答by Kyrsberg

<input type="text" class="form-control" id="employee" name="employee" [(ngModel)]="employeeDob" #date="ngModel" required />
<div [hidden]="date.valid || date.pristine"> <p>Please enter the date</p> </div>

<input type="text" class="form-control" id="employee" name="employee" [(ngModel)]="employeeDob" #date="ngModel" required />
<div [hidden]="date.valid || date.pristine"> <p>Please enter the date</p> </div>

straight outta documentation

直接输出文档

https://angular.io/docs/ts/latest/guide/forms.html

https://angular.io/docs/ts/latest/guide/forms.html

回答by Martin Brandl

pristine is true if the user has not interactedwith the form yet. You probably want to check for dirtyinstead? You can also use the hiddentag and replace

如果用户尚未与表单进行交互,则pristine 为真。你可能想检查吗?您也可以使用hidden标签并替换

<div *ngIf="employeeDob.pristine">

with:

和:

<div [hidden]="employeeDob.pristine">