简体   繁体   English

Angular ngForm参考变量返回null

[英]Angular ngForm reference variable returns null

I have a model in my component class like so: 我在组件类中有一个模型,如下所示:

agentDetailsCompany: ICompanyDetails = {
 company_name: '',
 company_reg_number: '',
 website: '',
 agent_details: {
  contact_number: '',
  email_address: '',
  physical_address: '',
},
 agent_type: '',
};

...
isComponentActive = true;
... 
ngOnInit(): void {
this.agentDataService.agentDataObject$
.takeWhile(() => this.isComponentActive)
.subscribe(
  agentDetails => {
    this.agentDetailsCompany = agentDetails;
  },
  err => {...});
}

And a component template like: 还有一个组件模板,如:

<form #myForm="ngForm">
  <input name="companyName" [(ngModel)]="agentDetailsCompany.company_name">
  ...
</form>
{{myForm.value | json}} //this here gives me an error that myForm is undefined
{{myForm?.value | json}} //this returns me null

I did import the forms module in my feature module: 我确实将表单模块导入了我的功能模块:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
...
imports: [
    FormsModule
 ...
],

I am giving data to the agentDetailsCompany object in the ngOnInit hook, inside a subscription of a BehaviorSubject as an observable, which is initialized with null. 我正在将数据提供给ngOnInit钩子中的agentDetailsCompany对象,该对象在BehaviorSubject的预订中作为可观察的对象,该对象以null初始化。

The parent of the this component is the one passing an object with values to the BehaviorSubject as an observable, thus the form data is available when the template is rendered. 此组件的父级是将具有值的对象作为可观察对象传递给BehaviorSubject的父级,因此在呈现模板时可以使用表单数据。

When the form is rendered, the fields are filled with values from ngOnInit, but the ngForm is still undefined, am I missing something here, please assist me guys. 呈现表单时,字段中填充了ngOnInit中的值,但是ngForm仍未定义,我在这里是否缺少任何内容,请协助我。

I have read the angular docs for both template driven and model driven forms but nowhere there is clue of the cause of my issue. 我已经阅读了模板驱动和模型驱动形式的docs,但是没有地方找到导致我问题的线索。

I am using angular 4, could this have an effect? 我正在使用角度4,这会产生影响吗? thanks. 谢谢。

I made an error by placing the log out of the div, 我将日志从div中移出了错误,

<div *ngIf="...">
  <form #myForm="ngForm">
    <input name="companyName" [(ngModel)]="agentDetailsCompany.company_name">
  </form>
</div>

{{myForm.value | json}} //this here was undefined because I had a div that wrapped the form and it had a condition to decide if to render the form.    

so the ref variable was really undefined by the time I was trying to log it. 所以在我尝试记录它时,ref变量确实是未定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM