简体   繁体   English

Angular 4:在ngOnInit()方法下,无法获取表单元素的值。 'get' 是未定义的错误来了

[英]Angular 4: under ngOnInit() method, unable to get the value of form element. 'get' is undefined error is coming

Description:描述:

Angular 4, Reactive Approach, trying to compare the field values by creating a validator function and passing that function under the ngOnInit() method. Angular 4,反应式方法,尝试通过创建验证器 function 并在 ngOnInit 下传递 function 来比较字段值()

Please find my code below,请在下面找到我的代码,

import { Component, OnInit } from '@angular/core';
import {BsModalRef} from "ngx-bootstrap";
import {FormGroup, FormControl, Validators} from "@angular/forms";

@Component({
  selector: 'app-formcontent',
  templateUrl: './formcontent.component.html',
  styleUrls: ['./formcontent.component.css']
})

export class FormcontentComponent implements OnInit {

  signupForm: FormGroup;
  constructor(public bsModalRef: BsModalRef) { }

ngOnInit() {
    this.signupForm = new FormGroup({
      'firstname': new FormControl(null, Validators.required),
      'lastname': new FormControl(null, Validators.required),
      'email': new FormControl(null, [Validators.required, Validators.email]),
      'password': new FormControl(null, Validators.required),
      'cnfpwd': new FormControl(null, [Validators.required, this.checkPassword.bind(this)]),
     'checkb': new FormControl('checked', Validators.required)
    });
  }

 checkPassword(control: FormControl): {[s: string]: boolean} {
    if(control.value === this.signupForm.get('password').value){
      return {'isConfirmPasswordValid': true}
    }
    return null;
  }

  onSubmit(){
    console.log(this.signupForm.value.firstname);
    console.log(this.signupForm.valid);
  }

}

In the above code I have created 'checkPassword' validator function to compare the control value with the password value.在上面的代码中,我创建了“checkPassword”验证器 function 来比较控制值和密码值。 When I pass this function under the ngOnInit() method as a part of validator function to the field 'cnfpwd', under runtime, I'm getting this below error.当我在 ngOnInit() 方法下将这个 function 作为验证器 function 的一部分传递给字段“cnfpwd”时,在运行时,我收到以下错误。

FormcontentComponent_Host.html:1 ERROR TypeError: Cannot read property 'get' of undefined
    at FormcontentComponent.webpackJsonp.../../../../../src/app/formcontent/formcontent.component.ts.FormcontentComponent.checkPassword (formcontent.component.ts:28)
    at forms.es5.js:443
    at Array.map (<anonymous>)
    at _executeValidators (forms.es5.js:443)
    at FormControl.validator (forms.es5.js:399)
    at FormControl.webpackJsonp.../../../forms/@angular/forms.es5.js.AbstractControl._runValidator (forms.es5.js:2645)
    at FormControl.webpackJsonp.../../../forms/@angular/forms.es5.js.AbstractControl.updateValueAndValidity (forms.es5.js:2613)
    at new FormControl (forms.es5.js:2936)
    at FormcontentComponent.webpackJsonp.../../../../../src/app/formcontent/formcontent.component.ts.FormcontentComponent.ngOnInit (formcontent.component.ts:22)
    at checkAndUpdateDirectiveInline (core.es5.js:10836)
View_FormcontentComponent_Host_0 @ FormcontentComponent_Host.html:1
proxyClass @ compiler.es5.js:14971
webpackJsonp.../../../core/@angular/core.es5.js.DebugContext_.logError @ core.es5.js:13398
webpackJsonp.../../../core/@angular/core.es5.js.ErrorHandler.handleError @ core.es5.js:1080
(anonymous) @ core.es5.js:9216
(anonymous) @ platform-browser.es5.js:2651
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:424
onInvokeTask @ core.es5.js:3881
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:423
webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask @ zone.js:191
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:498
invokeTask @ zone.js:1370
globalZoneAwareCallback @ zone.js:1388
FormcontentComponent_Host.html:1 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 0, nodeDef: {…}, elDef: {…}, elView: {…}}
View_FormcontentComponent_Host_0 @ FormcontentComponent_Host.html:1
proxyClass @ compiler.es5.js:14971
webpackJsonp.../../../core/@angular/core.es5.js.DebugContext_.logError @ core.es5.js:13398
webpackJsonp.../../../core/@angular/core.es5.js.ErrorHandler.handleError @ core.es5.js:1085
(anonymous) @ core.es5.js:9216
(anonymous) @ platform-browser.es5.js:2651
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:424
onInvokeTask @ core.es5.js:3881
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:423
webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask @ zone.js:191
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:498
invokeTask @ zone.js:1370
globalZoneAwareCallback @ zone.js:1388
FormcontentComponent.html:2 ERROR Error: formGroup expects a FormGroup instance. Please pass one in.

       Example:


    <div [formGroup]="myGroup">
      <input formControlName="firstName">
    </div>

    In your class:

    this.myGroup = new FormGroup({
       firstName: new FormControl()
    });
    at Function.webpackJsonp.../../../forms/@angular/forms.es5.js.ReactiveErrors.missingFormException (forms.es5.js:4437)
    at FormGroupDirective.webpackJsonp.../../../forms/@angular/forms.es5.js.FormGroupDirective._checkFormPresent (forms.es5.js:4858)
    at FormGroupDirective.webpackJsonp.../../../forms/@angular/forms.es5.js.FormGroupDirective.ngOnChanges (forms.es5.js:4688)
    at checkAndUpdateDirectiveInline (core.es5.js:10833)
    at checkAndUpdateNodeInline (core.es5.js:12332)
    at checkAndUpdateNode (core.es5.js:12271)
    at debugCheckAndUpdateNode (core.es5.js:13132)
    at debugCheckDirectivesFn (core.es5.js:13073)
    at Object.eval [as updateDirectives] (FormcontentComponent.html:2)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13058)
View_FormcontentComponent_0 @ FormcontentComponent.html:2
proxyClass @ compiler.es5.js:14971
webpackJsonp.../../../core/@angular/core.es5.js.DebugContext_.logError @ core.es5.js:13398
webpackJsonp.../../../core/@angular/core.es5.js.ErrorHandler.handleError @ core.es5.js:1080
(anonymous) @ core.es5.js:4814
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:391
webpackJsonp.../../../../zone.js/dist/zone.js.Zone.run @ zone.js:141
webpackJsonp.../../../core/@angular/core.es5.js.NgZone.runOutsideAngular @ core.es5.js:3844
webpackJsonp.../../../core/@angular/core.es5.js.ApplicationRef_.tick @ core.es5.js:4814
(anonymous) @ core.es5.js:4684
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:391
onInvoke @ core.es5.js:3890
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:390
webpackJsonp.../../../../zone.js/dist/zone.js.Zone.run @ zone.js:141
webpackJsonp.../../../core/@angular/core.es5.js.NgZone.run @ core.es5.js:3821
next @ core.es5.js:4684
schedulerFn @ core.es5.js:3635
webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.next @ Subscriber.js:185
webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber._next @ Subscriber.js:125
webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next @ Subscriber.js:89
webpackJsonp.../../../../rxjs/Subject.js.Subject.next @ Subject.js:55
webpackJsonp.../../../core/@angular/core.es5.js.EventEmitter.emit @ core.es5.js:3621
checkStable @ core.es5.js:3855
onLeave @ core.es5.js:3934
onInvokeTask @ core.es5.js:3884
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:423
webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask @ zone.js:191
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:498
invokeTask @ zone.js:1370
globalZoneAwareCallback @ zone.js:1388
FormcontentComponent.html:2 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 4, nodeDef: {…}, elDef: {…}, elView: {…}}

Unable to find solution, could you please point me out to any solution?无法找到解决方案,请您指出任何解决方案吗? Thanks.谢谢。

You should create the reactive form in the component constructor not ngOnInit.您应该在组件构造函数中创建响应式表单,而不是 ngOnInit。 https://angular.io/guide/reactive-forms#introduction-to-formbuilder https://angular.io/guide/reactive-forms#introduction-to-formbuilder

Andre is right.安德烈是对的。 You are examining the FormGroup before it gets instantiated.您在FormGroup实例化之前对其进行检查。 To fix your error, change the checkPassword function and any other validators to check if the FormGroup exists first, before doing the work.要修复您的错误,请在执行工作之前先更改checkPassword function 和任何其他验证器以检查FormGroup存在。

checkPassword(control: FormControl): {[s: string]: boolean} {
  if (!this.signupForm) {
    return null;
  }

  if(control.value === this.signupForm.get('password').value){
    return {'isConfirmPasswordValid': true}
  }
  return null;
}

hey i got an error like your and i found a solution, you should put the get function or any from filling above the Form, so when the page loaded the sever will call the get function firstly, here what i did in my own code嘿,我遇到了像你这样的错误,我找到了解决方案,你应该把 get function 或任何从填写表格上方,所以当页面加载时,服务器将首先调用 get function,这是我在自己的代码中所做的

constructor(private filterService: FilterService,private pageService: PageService, private clubsService: ClubsService, private router: Router,
    private route: ActivatedRoute ,private formBuilder: FormBuilder) { 
      this.route.paramMap.subscribe((params: ParamMap) => {
        this.idPage = Number(params.get('id'))
        this.getpage();
      this.myForm = this.formBuilder.group({
        id: [],
        pageName: ['', [Validators.required]],
        urlPage: ['', [Validators.required]],
            });

         
            })
    }

  ngOnInit(): void {
    // this.getpage();
    // this.route.paramMap.subscribe((params: ParamMap) => {
    //           this.idPage = Number(params.get('id'))
    //           this.getpage();
    //         })

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

相关问题 无法在订阅角度的ngoninit中获得价值 - Can't get value in ngoninit on subscribe angular Angular 4 @Input()值在ngOnInit()中未定义 - Angular 4 @Input() value is undefined in ngOnInit() Angular 2+ NgOnInit 为输入数组赋值但抛出未定义的错误 - Angular 2+ NgOnInit assigning value to input array but throws an error of undefined 如何使用Angular 4中的Reactive表单在ngOnInit上获取下拉列表的默认选定值 - How to get the default selected value of dropdown on ngOnInit using Reactive form in Angular 4 通过在ngOnInit()之外订阅get方法在组件中未定义属性 - property is undefined in component by subscribe to get method outside of ngOnInit() Angular,使用存储元素调用 ngOnInit 中的方法(订阅) - Angular, calling Method in ngOnInit with Store Element (Subscribe) IE9中的Angular 1/2混合应用程序错误:“ TypeError:无法获取属性&#39;ref&#39;的值:对象为null或未定义” - Angular 1/2 hybrid app error in ie9: “TypeError: Unable to get value of the property 'ref': object is null or undefined” 无法通过 Angular 中的 ngOnInit 通过 Observable 从 http.get 获取数据 - Unable to get data from http.get via Observable via ngOnInit in Angular 在ngOnInit上未定义Angular 2属性 - Angular 2 attribute is undefined on ngOnInit 如何从 ngOnInit Angular 中的服务获取数据 - How to get data from a service in ngOnInit Angular
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM