[英]Angular2 and ngIf
以下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"
錯誤消息未顯示。
我想念什么? 謝謝AG
我認為您需要通過放置=“ ngControl”或=“ ngModel”來指定#所指代的模板變量類型
<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>
在app.module.ts中添加了具有firstName和注釋屬性的類Contact導入了FormsModule在ContactFormComponent類型中添加了屬性和類型為Contact的初始化模型
<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上的示例之后進行了更改,現在該組件可以按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.