【问题标题】:Error when trying to use a property for [(value)]尝试将属性用于 [(value)] 时出错
【发布时间】:2020-01-08 21:57:18
【问题描述】:

我想选择存储在我的数据库中的选项字段。

<mat-form-field>
  <mat-select [(value)]="this.entities.gender" #gender formControlName="gender">
    <mat-option value="f">Female</mat-option>
    <mat-option value="m">Male</mat-option>
  </mat-select>
</mat-form-field>
private entities: IprofileData;

async ngOnInit() {
  this.entities = await this.profileService.getEntities().pipe(take(1)).toPromise();
  console.log(this.entities); // <-- This returns all the data that I need
}

但我得到了错误:

ERROR TypeError: Cannot read property 'gender' of undefined

为什么我无法使用this.entities


更新

我也尝试过使用 FormGroup 设置默认值

  private profileFormGroup = this.fb.group({
    gender: this.entities.gender
  });

但我得到了错误

错误:未捕获(承诺中):TypeError:无法读取未定义的属性“性别”

【问题讨论】:

  • 你试过安全导航算子吗?像这样:this.entities?.gender.
  • @R.Richards 如果我这样做,我会收到错误 '?.'运算符不能在赋值中使用
  • 试试entities.gender 没有this
  • @R.Richards 我做了,但我仍然收到错误 Cannot read property 'gender' of undefined
  • 您是否在应用程序中使用reactive forms?如果是这样,则需要在表单组中设置默认值。

标签: angular typescript


【解决方案1】:

不要将valueformControlName 一起使用,请使用formControlName

模板

<mat-form-field>
  <mat-select #gender formControlName="gender">
    <mat-option value="f">Female</mat-option>
    <mat-option value="m">Male</mat-option>
  </mat-select>
</mat-form-field>

组件.ts

private entities: IprofileData;

async ngOnInit() {
  this.entities = await 
  this.profileService.getEntities().pipe(take(1)).toPromise();
  console.log(this.entities); // <-- This returns all the data that I need
  // you need to put the value into formGroup
  this.profileFormGroup.get('gender').patchValue(this.entities.gender);
}

【讨论】:

    【解决方案2】:

    首先,你不能在模板中使用this

    第二,你不能在模板中使用private属性,它们必须是公共的。

    第三,我建议你坚持使用 observable 而不是 promise,这里有一个更好的解决方案

    <mat-form-field>
      <mat-select [(value)]="entities$ | async as entities" #gender
          formControlName="entities?.gender">
        <mat-option value="f">Female</mat-option>
        <mat-option value="m">Male</mat-option>
      </mat-select>
    </mat-form-field>
    
    entities$: Observable<IprofileData>;
    
    ngOnInit() {
      this.entities$ = this.profileService.getEntities().pipe(take(1));
    }
    

    【讨论】:

    • 我在 [entities$ | 的第 19 列收到错误 Unexpected token 'as'异步作为实体]。如果我删除 as entities,我会收到错误 Cannot have a pipe in an action expression at column 13 in [entities$ | async=$event]
    猜你喜欢
    • 2020-08-29
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    相关资源
    最近更新 更多