Aar*_*rsh 2 angular2-forms angular2-template angular2-services angular
我尝试了很多解决方案,但没有一个能帮助我解决这个问题......无法弄清楚我的代码中有什么问题......
HTML 代码 ::
<input type="text" class="form-control" placeholder="Please Enter Your Username" [(ngModel)]="currentUser.UserName" minlength="3" required id="userNameBox" name="UserName" #uName="ngModel">
Run Code Online (Sandbox Code Playgroud)
组件代码 ::
profile() {
let uid = Number(sessionStorage.getItem('id'));
this._homeService.profile(uid).subscribe(
res => {
this.currentUser = res
console.log(this.currentUser);
});
Run Code Online (Sandbox Code Playgroud)
服务 ::
profile(id: number) {
return this._http.get(url, id).map(
(res: Response) => {
console.log(res.json())
return new User(res.json()
) }
).catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)
模型 ::
export class User {
constructor(json: any) {
if (json != null) {
this.Id = json.Id;
this.UserName = json.UserName;
this.FirstName = json.FirstName;
this.LastName = json.LastName;
this.Gender = json.Gender;
this.Password = json.Password;
this.Email = json.Email;
}
}
Id: number = 0;
UserName: string = "";
FirstName: string = "";
LastName: string = "";
Gender: string = "";
Password: string = "";
Email: string = "";
Run Code Online (Sandbox Code Playgroud)
}
当您使用时[(ngModel)]
:
你必须这样做,你不能使用 safe operator ?
with 2 way data binding
:
<div *ngIf="currentUser.UserName">
<input type="text" class="form-control" placeholder="Please Enter Your Username" [(ngModel)]="currentUser.UserName" minlength="3" required id="userNameBox" name="UserName" #uName="ngModel">
</div>
Run Code Online (Sandbox Code Playgroud)
或者
创建具有默认属性的初始对象:
this.currentUser = {
'UserName' : '',
'Email' : '',
// other properties , that you are using on template side
}
Run Code Online (Sandbox Code Playgroud)
这是第二种方法的工作演示的链接:
https://stackblitz.com/edit/angular-initial-value
归档时间: |
|
查看次数: |
6620 次 |
最近记录: |