【问题标题】:Error- Cannot read property 'controls' of null (Reactive Form- Adding a FormArray)错误 - 无法读取 null 的属性“控件”(反应式表单 - 添加 FormArray)
【发布时间】:2018-06-11 16:10:58
【问题描述】:

我面临一个错误,无法弄清楚为什么显示此错误需要一些帮助:

无法读取 null 的属性“控件”

这是我的代码 TS(不是通过我正在初始化表单的函数粘贴整个代码,实际上它正在捕获错误):

ngOnInit() {
 this.route.params
 .subscribe(
 (params: Params) => {
     this.id = +params['id'];
     this.editMode = params['id'] != null;
     this.initForm();});
 }



quesControl() {
   line 79:  console.log(this.constructor.name);
   line 80: console.log(this.questionaireForm.get('steerings'));
    return (<FormArray>this.questionaireForm.get('steerings')).controls;
}


private initForm() {
    let questionaireName     = '';
    let questionaireTitle    = '';
    let questionaireType     = '';
    let questionaireLevel    = '';
    let questionaireGroup    = '';
    const questionaireSteerings = new FormArray([]);

    if (this.editMode) {
      this.questionaireService.getQuestionaireById(this.id).subscribe(
        (questionaireRec: Questionaire) => {
          questionaireName  = questionaireRec.name;
          questionaireTitle = questionaireRec.title;
          questionaireType  = questionaireRec.type;
          questionaireLevel = questionaireRec.level;
          questionaireGroup = questionaireRec.group;
          this.questionaireForm = new FormGroup ({
            'name'    : new FormControl (questionaireName,  Validators.required),
            'title'   : new FormControl (questionaireTitle, Validators.required),
            'type'    : new FormControl (questionaireType,  Validators.required),
            'level'   : new FormControl (questionaireLevel, Validators.required),
            'group'   : new FormControl (questionaireGroup, Validators.required)
          });
          if (questionaireRec['steerings']) {
            for (const steeringCtrl of questionaireRec.steerings) {
              line 110: console.log(steeringCtrl);
              questionaireSteerings.push(
               new FormGroup({
                 'proposal': new FormControl (steeringCtrl.proposal, Validators.required),
                 'label': new FormControl (steeringCtrl.label, Validators.required),
                 'product': new FormControl (steeringCtrl.product, Validators.required)
               })
              );
            }
          }
        }
      );
    }
      this.questionaireForm = new FormGroup ({
        'name'    : new FormControl (questionaireName,  Validators.required),
        'title'   : new FormControl (questionaireTitle, Validators.required),
        'type'    : new FormControl (questionaireType,  Validators.required),
        'level'   : new FormControl (questionaireLevel, Validators.required),
        'group'   : new FormControl (questionaireGroup, Validators.required),
        'steerings': questionaireSteerings
      });
  }

包含作为数组的转向模型的数据模型问卷:

const questionaire: Questionaire[] = [
 new Questionaire(0, 'Questionaire for NRR consumer customer', '58ABC', '57ABC', '11/10/2016','NRR', 'greyCase', 'Proposal', 'general'),
 new Questionaire(1, 'Questionaire for RR customer', '7865C', '58ABC', '12/30/2017','RR', 'regulatory', 'credit', 'mortgage',[
 new Steerings('proposal', 'equal', 'ok'),new Steerings('proposal', 'equal', 'ok')]),
 new Questionaire(2, 'Questionaire for loan demanding customers', '58ABC', '', '','Loan', 'greyCase', 'credit', 'risk', [
 new Steerings('proposal', 'equal', 'ok')])
 ];

还有 HTML 代码:

<div class="col-xs-12" formArrayName = "steerings">
 <div class="row" *ngFor = "let quesCtrl of quesControl(); let i = index" [formGroupName] = "i">

 <div class="col-xs-4">
  <label for="proposal">Proposal Type</label>
  <select class="form-control" id="proposal" formControlName="proposal" #proposal>
  <option value="">Select</option>
  <option value="Proposal">Proposal</option>
  <option value="ndg">NDG</option>
  <option value="credit">Credit Line</option> 
  <option value="collateral">Collateral</option>
  <option value="asset">Asset</option> 
 </select>
 </div>

 <div class="col-xs-4">
 <label for="Label">Label</label>
 <select class="form-control" id="label" formControlName="label" #label>
 <option value="">Select</option>
 <option value="equal">Equal</option>
 <option value="notEqual">Not equal</option>
 <option value="greater">Greater than</option>
 <option value="less">Less than</option>
 <option value="con">Contained in a list</option>
 <option value="ntCon">Not Contained in a list</option>
 </select> 
 </div>

 <div class="col-xs-4">
 <label for="name">PRODUCT</label>
 <input type="text" class="form-control" id="product" formControlName="product" #product>
 </div>

 </div>
 </div>

提前致谢!

问候

阿德南

【问题讨论】:

  • 将有效的返回类型添加到function
  • @arvind 关于哪个功能抱歉我不明白?

标签: angular typescript angular-reactive-forms


【解决方案1】:

代码的重要部分似乎在这里:

quesControl() {
    return (<FormArray>this.questionaireForm.get('steerings')).controls;
}

这是相同方法的快速调试版本,它将帮助您解决问题...

quesControl() {
    // Check this logs the class name, otherwise you've lost the context of this
    console.log(this.constructor.name);

    // Check what you get back here... is it null, or of the wrong type
    console.log(this.questionaireForm.get('steerings'));

    return (<FormArray>this.questionaireForm.get('steerings')).controls;
}

如果您需要深入挖掘,也可以使用typeof 记录变量的类型。

【讨论】:

  • 感谢您的建议,我已经尝试过了。这就是表单数组采用空值的原因,不知道为什么。请您帮帮我..
  • 我已经添加了日志的图像..你能找出问题吗?
  • 你知道为什么它会调用quesControl 三次吗?在第三次调用中,this.questionaireForm.get('steerings') 为空 - 但前两次调用显示它不为空。
  • 您好,感谢您的帮助,我找到了问题所在。问题是在表单组中,我没有传递转向表单控件,因此在订阅终止后它变成了 null。
猜你喜欢
  • 2021-04-27
  • 1970-01-01
  • 2022-01-18
  • 2021-06-07
  • 2021-03-16
  • 2021-01-19
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
相关资源
最近更新 更多