【发布时间】:2019-08-25 05:05:32
【问题描述】:
我来了
TypeError:无法读取属性“firstName”
当我加载我的响应式表单时。表单行为似乎是正确的。我的数据正在填充到表单中,但我仍然收到此错误。
我查看了有关此问题的先前问题,答案似乎不适用于我的特定案例。
这是我的UserComponent:
export class UserComponent implements OnInit, OnDestroy {
user: User;
userId: string;
userChangedSub = new Subscription();
form: FormGroup;
constructor(private userService: UserService) {
}
ngOnInit() {
console.log('ngOnInit started');
this.userId = this.userService.getUserId();
this.userChangedSub = this.userService.getUser(this.userId).subscribe(user => {
console.log('email is: ' + user.email);
this.user = user;
console.log(this.user);
});
this.form = this.createFormGroup();
}
createFormGroup() {
return new FormGroup({
first: new FormControl('', {validators: Validators.required}),
last: new FormControl('', {validators: Validators.required})
});
}
onSubmit() {
}
ngOnDestroy() {
this.userChangedSub.unsubscribe();
}
}
这是我的表格:
<section class="user-form">
<form fxLayout="column" fxLayoutAlign="center center" [formGroup]="form" (ngSubmit)="onSubmit()">
<mat-form-field>
<input matInput type="text" *ngIf="user.firstName!==undefined" [value]="user.firstName" formControlName="first">
</mat-form-field>
<mat-form-field>
<input matInput type="text" [value]="user.lastName" formControlName="last">
</mat-form-field>
<button type="submit" [disabled]="!form.valid"></button>
</form>
</section>
表单显示登录用户的正确名字和姓氏,但我仍然收到此错误。我检查了表单中的 user.firstName 是否未定义。我认为这会删除TypeError。
【问题讨论】:
标签: angular angular-reactive-forms