【问题标题】:Cannot read property 'setValue' of undefined | Angular无法读取未定义的属性“setValue”|角
【发布时间】:2020-03-16 23:14:05
【问题描述】:

我的 HTML 组件有问题,由于某种原因,我的方法显示错误: 当我单击编辑按钮时,无法读取未定义的属性“setValue”,但一切似乎都正常。

这是我的 HTML

<div *ngFor="let item of currentUser.myExperiences" class="mt-3">
        <div>
          <h6>{{item.companyName}} <span *ngIf="item.currentlyWorking" class="badge badge-warning">Currently
              working</span>
              <span class="float-right">
                <a class="text-warning cursor" (click)="openEditModal(item)"><i class="fas fa-pencil-alt"></i></a>
              </span>
            </h6>
          <p class="text-muted p-text-sm">{{item.functions}}</p>
          <p class="text-muted p-text-sm" *ngIf="item.references">
            <strong>References:</strong>
            {{item.references}}
          </p>
          <hr>
        </div>
      </div>

<form role="form" [formGroup]="updateForm">
        <div class="form-group">
          <label for="functions">Funtions</label>
          <input type="text" class="form-control" id="functions" name="functions" formControlName="functions" aria-describedby="emailHelp">
        </div>
        <div class="form-group">
          <label for="exampleInputPassword1">Password</label>
          <input type="password" class="form-control" id="exampleInputPassword1">
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
      </form>

这是我的 TS 组件:

public openEditModal(myExperience: IMyExperience): void {
console.log(myExperience);
// Set values to controls
console.log(myExperience.id);
this.experienceId.setValue(myExperience.id);
this.companyName.setValue(myExperience.companyName);
this.functions.setValue(myExperience.functions);
this.workedYears.setValue(myExperience.workedYears);
this.references.setValue(myExperience.references);
this.currentlyWorking.setValue(myExperience.currentlyWorking);

this.updateForm.setValue({
  experienceId: this.experienceId.value,
  companyName: this.companyName.value,
  functions: this.functions.value,
  workedYears: this.workedYears.value,
  references: this.references.value,
  currentlyWorking: this.currentlyWorking.value
});

// Open the modal
this.modalRef = this.modalService.show(
  this.editModal,
  Object.assign({}, { class: 'gray modal-lg' })
);}

我尝试在控制台中显示该对象,但效果很好,但我不确定为什么会这样。

我使用解析器将信息从路由正确传递到组件。

提前致谢。

【问题讨论】:

  • 这是一个不完整的代码,this.experienceId是什么?
  • 在 HTML 文件中,“item”包含与 TS 文件中相同的对象。问题是,当它被调试时,它会在 HTML 中显示错误
  • 我在您添加的问题中看不到它,您能否为您的问题创建一个堆栈闪电战?
  • 您能否分享完整的 TS 文件,因为我不确定您的 sn-p 中某些对象的类型和定义(例如 experienceId、companyName 等)

标签: html angular typescript


【解决方案1】:

尝试使用 this.updateForm.patchValue 而不是 this.updateForm.setValue。

【讨论】:

  • 它似乎没有工作,它显示类似的错误:无法读取未定义的属性'patchValue'。奇怪的是 console.log(myExperience);完美地显示对象。
  • 如果您提供完整的代码会更有帮助。
猜你喜欢
  • 2019-02-26
  • 1970-01-01
  • 2020-08-17
  • 2019-04-28
  • 2019-01-25
  • 2021-08-03
  • 2020-12-14
  • 2021-11-01
  • 2018-08-17
相关资源
最近更新 更多