angular 反应式表单抛出 "Cannot find control with name" 不相关的模型字段

angular reactive form throws "Cannot find control with name" for irrelevant model field

我正在尝试使用 Angular 响应式表单构建一个编辑组件。但是,我收到错误 "Error: Cannot find form control with name: created.","created" 在我的模型上是 属性。

但是,created 不是可编辑字段,不应绑定到表单。我没有在我的表单生成器中指定它,我的 edit.html 页面上也没有控件。它只出现在我的模型上。我如何告诉表单验证器忽略这个和其他不相关的模型属性?

这是我的模型:

        export class User {
      id: number;
      userName: string;
      password: string;
      passwordHash: string;
      lastName: string;
      firstName: string;
      email: string;
      created: string;
      lastLogin: string;
      description: string;
      isSaved: boolean;
      passsword:string;
      passwordConfirm:string;
    }

这是我的组件:

    import { Component, OnInit, Inject } from '@angular/core';
import { Router } from "@angular/router";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { first } from "rxjs/operators";
import { User } from "../../model/user.model";
import { UserService } from "../../service/user.service";


@Component({
  selector: 'app-edit-user',
  templateUrl: './edit-user.component.html',
  styleUrls: ['./edit-user.component.css']
})
export class EditUserComponent implements OnInit {

  user: User;
  editForm: FormGroup;

  constructor(private formBuilder: FormBuilder, private router: Router, private userService: UserService) { }

  ngOnInit() {
    let userId = window.localStorage.getItem("editUserId");
    if (!userId) {
      alert("Invalid action.")
      this.router.navigate(['list-user']);
      return;
    }
    this.editForm = this.formBuilder.group({
      id: [''],
      userName: ['', Validators.required],
      password: ['', Validators.required],
      passwordConfirm: ['', Validators.required],
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      email: ['', Validators.email],
      description: [''],
    });
    this.userService.getUserById(+userId)
      .subscribe(data => {
        this.editForm.setValue(data);
      });
  }

  onSubmit() {

    if(!this.editForm.value.passwordConfirm){
      console.log("password confirmed is undefined. Setting");
      this.editForm.value.passwordConfirm = this.editForm.value.password;
    }

    this.userService.updateUser(this.editForm.value)
      .pipe(first())
      .subscribe(
        data => {
          alert('User updated successfully.');
          this.router.navigate(['list-user']);
        },
        error => {
          alert("En error occured and changes should not be saved. Details: " + error);
        });
  }
}

这是我的 html:

        <div class="col-md-6 user-container">
          <h2 class="text-center">Edit User</h2>
          <form [formGroup]="editForm" (ngSubmit)="onSubmit()">

            <div class="hidden" style="display:none;">
              <input type="text" formControlName="id" placeholder="id" name="id" class="form-control" id="id">
            </div>

            <!-- todo: replace display none with bootstrap class -->

            <div class="form-group" style="display:none;">
              <input type="text" formControlName="userName" placeholder="userName" name="userName" class="form-control"
                id="userName" readonly="true">
            </div>

            <div class="form-group">
              <label for="firstName">First Name:</label>
              <input formControlName="firstName" placeholder="First Name" name="firstName" class="form-control" id="firstName">
            </div>

            <div class="form-group">
              <label for="lastName">Last Name:</label>
              <input formControlName="lastName" placeholder="Last name" name="lastName" class="form-control" id="lastName">
            </div>

            <div class="form-group">
              <label for="email">Email:</label>
              <input formControlName="email" placeholder="email" name="email" class="form-control" id="email">
            </div>

            <div class="form-group">
              <label for="description">Description:</label>
              <input formControlName="description" placeholder="Description" name="description" class="form-control"
                id="description">
            </div>

            <hr>

            <h5>Change password</h5>

            <div class="form-group">
              <label for="password">New password:</label>
              <input type="password" formControlName="password" placeholder="password" name="password" class="form-control"
                id="password">
            </div>

            <div class="form-group">
              <label for="passwordConfirm">Confirm password:</label>
              <input type="password" formControlName="passwordConfirm" placeholder="passwordConfirm" name="passwordConfirm"
                class="form-control" id="passwordConfirm">
            </div>

            <button class="btn btn-success">Update</button>
          </form>
        </div>

错误详情如下:

错误:找不到名称为:已创建的表单控件。 core.js:5847 留言:"Cannot find form control with name: created." 堆栈:"Error: Cannot find form control with name: created.\n at FormGroup._throwIfControlMissing (https://localhost:5001/vendor.js:70056:19)\n at https://localhost:5001/vendor.js:69913:19\n at Array.forEach ()\n at FormGroup.setValue (https://localhost:5001/vendor.js:69912:28)\n at SafeSubscriber._next (https://localhost:5001/main.js:1937:28)\n at SafeSubscriber.__tryOrUnsub (https://localhost:5001/vendor.js:95425:16)\n at SafeSubscriber.next (https://localhost:5001/vendor.js:95363:22)\n at Subscriber._next (https://localhost:5001/vendor.js:95309:26)\n at Subscriber.next (https://localhost:5001/vendor.js:95286:18)\n at MapSubscriber._next (https://localhost:5001/vendor.js:100330:26)"

您似乎想将一个 User 对象设置到表单中,该表单没有名为 created 的控件。

您要么从传递给 setValue 的对象中删除该字段,要么不使用 setValue 而使用 patchValue,这似乎忽略了未知字段,并且只涉及那些在传入的对象中指定的控件并单独保留其他控件,而不是 setValue,它重置那些未在传入的对象中指定的控件。

Angular 反应式表单只接受表单生成器中存在的那些值,如果对象中有一些额外的属性,您正在使用它来设置值,它会给出错误 属性 .在这里,你有额外的 created,如果你以某种方式解决了那个错误,它会再次给 lastLogin 错误,因为它不是表单构建器的一部分。

this.userService.getUserById(+userId)
  .subscribe(data => {
   const propertyToSelect = ['id','userName', 'password','passwordConfirm', 'firstName', 'lastName','email', 'description']
   const objectToSetValue = propertyToSelect.map((property) => {property: data[property]})
   this.editForm.setValue(objectToSetValue);
  });