错误:尚未向该组注册任何表单控件。如果您使用 ngModel,您可能需要检查下一个刻度(例如使用 setTimeout)

2023-12-27

I am using template driven form and am trying to set the value of the form elements based on some object properties, however i face the following Error on doing so. Also here is my code for the TD form and how i am trying to access it.

.html 文件:

<div class="row">
  <div class="col-xs-12">
    <form (ngSubmit)="onAddDevice(f)" #f="ngForm">
      <div class="row">
        <div class="col-sm-5 form-group">
          <label for="name">Name</label>
          <input type="text" id="name" class="form-control" name="name" ngModel required>
        </div>
        <div class="col-sm-2 form-group">
          <label for="type">Type</label>
          <input type="text" id="type" class="form-control" name="type" ngModel required>
        </div>
        <div class="col-sm-5 form-group">
          <label for="platform">Platform</label>
          <input type="text" id="platform" class="form-control" name="platform" ngModel required>
        </div>
        <div class="col-sm-2 form-group">
          <label for="udid">UDID</label>
          <input type="text" id="udid" class="form-control" name="udid" ngModel required>
        </div>
      </div>

      <div class="row">
        <div class="col-xs-12">
          <button class="btn btn-success" type="submit" [disabled]="!f.valid">Add</button>
          <button class="btn btn-danger" type="button">Delete</button>
          <button class="btn btn-primary" type="button">Clear</button>
        </div>
      </div>
    </form>
  </div>
</div>

.ts 文件:

  @ViewChild('f') deviceForm: NgForm;
  @Output() deviceAdded = new EventEmitter<DeviceModel>();
  editedItemIndex: number;
  editedDevice: DeviceModel;

  constructor(private deviceService: DeviceService, private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.params
      .subscribe(
        (params: Params) =>{
            this.id = +params['id'];
            this.editMode = params['id'] != null;
            if ( this.editMode) {
              this.editedItemIndex = params['id'];
              this.editedDevice = this.deviceService.getDevice(params['id']);
              console.log(this.editedDevice.frame);
              this.deviceForm.setValue({
                name: this.editedDevice.name,
                platform: this.editedDevice.platform,
                type: this.editedDevice.type,
                udid: this.editedDevice.frame
              });
            }
        }
      );
  }

问题是因为调用表单上的 setValue 方法。


我遇到了同样的问题,并通过这样做解决了它(下面的代码片段使用您的表单控件):

this.deviceForm.form.patchValue({
    name: this.editedDevice.name,
    platform: this.editedDevice.platform,
    type: this.editedDevice.type,
    udid: this.editedDevice.frame
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

错误:尚未向该组注册任何表单控件。如果您使用 ngModel,您可能需要检查下一个刻度(例如使用 setTimeout) 的相关文章

随机推荐