【问题标题】:Angular 2 Cannot read property 'subscribe' of null for form field when using Validators.patternAngular 2 使用 Validators.pattern 时无法读取表单字段的 null 属性“订阅”
【发布时间】:2018-06-27 04:46:09
【问题描述】:

我正在研究 Angular 2 反应式表单。我在使用 Validators.pattern() 进行表单字段验证时遇到问题。一旦我开始在输入字段中输入,就会得到异常Cannot read property 'subscribe' of null

打字稿代码

createForm(){
    this.jobForm = this.fb.group({
        name: ['', Validators.required, Validators.pattern(/^[a-zA-Z0-9]+$/)],
        epType: ['ENDPOINT_TYPE_SBC', Validators.required],
        streams : this.fb.array([
            this.createStreamControls(),
        ]),
        channels:this.fb.array([
            this.createChannelControls(),
        ])
    });        
}

'name' 属性根据模式进行验证。

HTML 代码

 <div class="ui-grid-col-8 ">
      <input id="name" formControlName="name" pInputText class="width-60" />
                    <br>
      <small *ngIf="jobForm.controls.name.hasError('required') && jobForm.controls.name.touched" class="text-danger">Required</small>
      <small *ngIf="jobForm.controls.name.hasError('pattern') && jobForm.controls.name.touched" class="text-danger">Should be alpha-numeric without space</small>
 </div>

正在尝试验证输入字段名称。

例外Cannot read property 'subscribe' of null

Image showing Exception

当我从 name 属性中删除 Validators.pattern() 时,它工作正常。我无法理解为什么它在这里失败,因为我已经以相同的形式将 Validators.pattern() 用于其他属性并且它对它们很好。

【问题讨论】:

  • 我觉得应该是[ '', Validators.compose([Validators.required, Validators.pattern(/^[a-zA-Z0-9]+$/)])]
  • 知道了。 @swaroop 强调了我正在做的错误。感谢您的帮助

标签: validation typescript angular2-forms


【解决方案1】:

需要在表单组的第二个参数中传递验证器数组。

createForm(){
    this.jobForm = this.fb.group({
        name: ['', [Validators.required, Validators.pattern(/^[a-zA-Z0-9]+$/)]],
        epType: ['ENDPOINT_TYPE_SBC', [Validators.required]],
        streams : this.fb.array([
            this.createStreamControls(),
        ]),
        channels:this.fb.array([
            this.createChannelControls(),
        ])
    });        
}

【讨论】:

  • 哦,是的,我的错。在过去的两天里,我一直被这个问题困扰。一个小错误对你造成了多大的影响。 :(感谢您的帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-18
  • 2018-09-02
  • 1970-01-01
  • 2016-09-30
  • 2017-06-28
  • 1970-01-01
相关资源
最近更新 更多