我正在将输入标记的值绑定到ngmodel。
<input type="text" id="Fname" value="{{getProfile.firstname}}" placeholder="FirstName" #FirstName/>
这是我的打字组件
export class EditprofileComponent implements OnInit {
getProfile: Profile;
constructor(private profileService: ProfileService)
ngOnInit() {
this.profileService.getProfile().subscribe(data =>{
this.getProfile = data;
console.log(data);
})
}
当我使用console.log(数据(时,控制台会写出一个Profile类型的对象。所以我得到了正确的数据
我对ngFor指令也做了同样的事情。但对于常规输入值,它不起作用。
如何将Profiles的名字绑定为输入标记的值?
它是异步的,因此您需要添加确保在组件渲染之前将数据加载到模板中。有几个选项可以解决这个问题:
简单解决方案
添加存在运算符/安全导航运算符?
(检查您的变量是否存在(:
getProfile?.firstname
或
用*ngIf
将您的输入封装在ng-container
中。
<ng-container *ngIf="getProfile">
// Add your input here
</ng-container>
最佳/更好的做法
使用解析程序确保在渲染组件之前加载数据。
https://alligator.io/angular/route-resolvers/
将语法更改为-
value="{{getProfile?.firstname}}"
您可以使用异步管道进行可观测(当组件被销毁时,它也会取消订阅,这样您就不必手动执行(,它看起来是这样的:
getProfile: Observable<Profile>;
ngOnInit() {
this.getProfile=this.profileService.getProfile();
}
html:
<input *ngIf="getProfile | async as profile" type="text" id="Fname" value="{{profile.firstname}}" placeholder="FirstName" #FirstName/>