![](/img/trans.png)
[英]How to bind in reactive forms which is the formcontrolname and ngmodel in angular
[英]How to normally bind forms in angular
我有一個模板表單,我是從指南中寫的,但是它們實際上並沒有起作用。 我有幾種模型:
export class User {
constructor(public userId?: UserId,
public firstName?: String,
public lastName?: String,
public address?: Address) {
}
}
export class Address {
constructor(
public street?: String,
public city?: String,
public zipCode?: String) {
}
}
我有組件:
Component({
templateUrl: 'user.html'
})
export class MyComponent implements OnInit, OnDestroy{
user: User;
userForm: NgForm;
ngOnInit(): void {
}
和頁面本身:
<form novalidate #userForm="ngForm">
<div class="form-group">
<input required minlength="4" type="text"
id="firstName"
[(ngModel)]="user.firstName" name="firstName">
<small *ngIf="!firstName.valid">Not valid!</small>
</div>
<div class="form-group">
<input required ng-minlength="4" type="text"
id="lastName"
[(ngModel)]="user.lastName" name="lastName">
</div>
<div ngModelGroup="user.address">
<div class="form-group">
<input required ng-minlength="4"
type="text"
id="address-house"
[(ngModel)]="user.address.address1" name="address.address1">
</div>
<div class="form-group">
<div class="form-group">
<input required ng-minlength="4"
type="text"
id="zipCode"
[(ngModel)]="user.address.zipCode" name="address.zipCode">
</div>
<div>
<input required ng-minlength="4"
type="text"
lass="form-control input-lg"
id="city"
[(ngModel)]="user.address.city" name="address.city">
</div>
</div>
</div>
<button type="button" (click)="checkAndProceed()">Continue</button>
</div>
</form>
我唯一想做的就是添加驗證-僅此而已。 沒有指南提供幫助。 我們可以進行HTML內驗證還是ts驗證? 單擊“繼續”按鈕並使其有效時,調用驗證將是一個不錯的選擇。
在驗證的情況下,我還會收到控制台錯誤: Cannot read property 'valid' of undefined
輸入元素上有很多屬性。 我們有名稱,ID和模板引用變量。 您的代碼缺少模板引用變量。 它是模板引用變量,它保留對元素的引用,並具有與之關聯的有效,臟和其他標志。
例如,更改您的代碼以包括如下模板引用變量:
<div class="form-group">
<input required minlength="4" type="text"
id="firstName"
[(ngModel)]="user.firstName" name="firstName"
#firstNameVar="ngModel">
<small *ngIf="!firstNameVar.valid">Not valid!</small>
</div>
注意#firstNameVar
。 那是模板引用變量。 可以將其命名為與您的ID和名稱屬性相同的名稱。 我只是將其命名為其他名稱,因此可以很容易地區分其他兩個屬性。
還要注意,然后將* ngIf更改為使用firstNameVar.valid
有關模板引用變量的更多信息,請參見: https : //angular.io/guide/template-syntax#ref-vars
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.