【问题标题】:New Reactive forms users. TypeError: Cannot read property 'firstName' of undefined新的反应式表单用户。 TypeError:无法读取未定义的属性“firstName”
【发布时间】: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


【解决方案1】:

加载组件时,userundefined,这就是您收到错误的原因。您可以通过几种方式解决此问题。将user: User; 更新为user: User = {}; 或更新您的HTML 以包含这些“空/未定义”检查,如下所示:&lt;input matInput type="text" *ngIf="user?.firstName!==undefined" [value]="user?.firstName" formControlName="first"&gt;

【讨论】:

  • 谢谢!我声明: user: User = { email: '', userId: '', firstName: '', lastName: '' };这消除了错误。
  • NOT USE [value] 你使用的是 ReactiveForm,你唯一需要的是 formControlName。您可以在定义&lt;form *ngIf="form"...&gt; 形式时使用
  • 我不明白这个问题。我将用户初始化为具有空字符串属性的用户。在 ngOnInit 中,我用我的 firestore 中的用户替换了这个用户。我不理解@peinearydevelopment
  • @CraigTaylor 抱歉,该评论是对另一位评论者的回应(但他们删除了他们的评论)。我已经把它删了。
  • @CraigTaylor 问题在于您如何创建表单。为什么不使用first: new FormControl(user.firstName, {validators: Validators.required}) 创建表单?这不是逻辑使用 [value] 和 formControlName。
猜你喜欢
  • 2019-01-25
  • 2021-08-03
  • 2021-01-14
  • 2022-09-27
  • 2020-09-07
  • 2021-06-22
  • 2021-07-10
  • 2017-01-01
  • 2021-01-16
相关资源
最近更新 更多