【问题标题】:Angular 4 - cannot read property status of null while displaying validation errorAngular 4 - 在显示验证错误时无法读取 null 的属性状态
【发布时间】:2018-06-18 09:50:29
【问题描述】:

我正在尝试显示FormArray 的验证错误,我在数组中有contact_number 和contact_name。这些字段已成功动态添加,但当它们无效时,我需要显示验证错误,但它给出以下错误:

ERROR TypeError: Cannot read property 'status' of null
    at Object.eval [as updateDirectives] (SignupComponent.html:82)
    at Object.debugUpdateDirectives [as updateDirectives] (services.ts:384)
    at checkAndUpdateView (view.ts:359)
    at callViewAction (view.ts:615)
    at execEmbeddedViewsAction (view.ts:580)
    at checkAndUpdateView (view.ts:360)
    at callViewAction (view.ts:615)
    at execComponentViewsAction (view.ts:559)
    at checkAndUpdateView (view.ts:370)
    at callViewAction (view.ts:615)

我的组件代码如下:

ngOnInit() {
    this.createForm();
}

createForm() {
    this.userGroup = this.fb.group({
        'name': [null, Validators.compose(
            [
                Validators.required,
                Validators.pattern("^[a-zA-Z]*$")
            ]
        )],
        'email': [null, Validators.compose(
            [
                Validators.required,
                Validators.email
            ]
        )],
        'age': [null, Validators.compose(
            [
                Validators.required,
                Validators.pattern("^[0-9]*$"),
                Validators.min(18)
            ]
        )],
        'address': this.fb.group({
            'address_1': [null, Validators.required],
            'address_2': null,
            'city': [null, Validators.required]
        }),
        'contacts': this.fb.array([this.initContact()])
    });
    console.log(this.userGroup);
}

initContact() {
    return this.fb.group({
        contact_name: ['', Validators.required],
        contact_number: ['', Validators.required]
    });
}

我的模板代码如下:

<div>
    <h4>Signup</h4>
    <div>
        <form [formGroup]="userGroup" #f="ngForm">
            <div class="form-group">
                <label for="name">Name</label>:
                <input type="text" formControlName="name" placeholder="Enter Name" />
                <span *ngIf="userGroup.get('name').touched && userGroup.get('name').status == 'INVALID'">
                <span *ngIf="userGroup.hasError('required','name')">Please enter name</span>
                <span *ngIf="userGroup.hasError('pattern','name')">Invalid name</span>
                </span>
            </div>

            <div class="form-group">
                <label for="email">Email</label>:
                <input type="text" formControlName="email" placeholder="Enter Email" />
                <span *ngIf="userGroup.get('email').touched && userGroup.get('email').status == 'INVALID'">
                    <span *ngIf="userGroup.hasError('required','email')">Please enter email</span>
                    <span *ngIf="userGroup.hasError('email','email')">Invalid email</span>
                </span>
            </div>

            <div class="form-group">
                <label for="age">Age</label>:
                <input type="text" formControlName="age" placeholder="Enter Age" />
                <span *ngIf="userGroup.get('age').touched && userGroup.get('age').status == 'INVALID'">
                    <span *ngIf="userGroup.hasError('required','age')">Please enter age</span>
                    <span *ngIf="userGroup.hasError('pattern','age')">Invalid age</span>
                    <span *ngIf="userGroup.hasError('min','age')">Min age should be 18 years</span>
                </span>
            </div>

            <div formGroupName="address">
                <h4>Adddress</h4>
                <div class="form-group">
                    <label for="address_1">Address 1</label>:
                    <input type="text" formControlName="address_1" placeholder="Enter Address 1" />
                    <span *ngIf="userGroup.get('address.address_1').touched && userGroup.get('address.address_1').status == 'INVALID'">
                        <span *ngIf="userGroup.hasError('required','address.address_1')">Please enter address line 1</span>
                    </span>
                </div>

                <div class="form-group">
                    <label for="address_2">Address 2</label>:
                    <input type="text" formControlName="address_2" placeholder="Enter Address 2" />
                </div>

                <div class="form-group">
                    <label for="city">City</label>:
                    <input type="text" formControlName="city" placeholder="Enter City" />
                    <span *ngIf="userGroup.get('address.city').touched && userGroup.get('address.city').status == 'INVALID'">
                        <span *ngIf="userGroup.hasError('required','address.city')">Please enter city</span>
                    </span>
                </div>
            </div>

            <div class="form-group" formArrayName="contacts">
                <label for="contacts">Contact</label>: <span><button (click)="addContact()">Add Contact</button></span>
                <div *ngFor="let cont of userGroup.controls.contacts.controls let i=index" [formGroupName]="i">
                    <div class="form-group">
                        <label for="contact_name" class="lbl_contact">Name</label>:
                        <input type="text" formControlName="contact_name" class="txt_contact" placeholder="Enter Name" />
                        <label for="contact_number" class="lbl_contact">Number</label>:
                        <input type="text" formControlName="contact_number" class="txt_contact" placeholder="Enter Number" />
                        <span *ngIf="userGroup.get('contacts.controls[i].controls.contact_name').touched && userGroup.get('contacts.controls[i].controls.contact_name').status == 'INVALID'">
                            <span *ngIf="userGroup.hasError('required','contacts.controls[i].controls.contact_name')">Please enter contact name</span>
                        </span>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <button type="submit" [disabled]="!f.valid" class="btn btn-primary">Sign Up</button>
            </div>
        </form>
    </div>
</div>

我没有得到错误是什么,因为它仅在我尝试显示联系人姓名或号码的错误时才给出错误。

【问题讨论】:

    标签: javascript angular angular4-forms angular-validation


    【解决方案1】:

    您尝试获取元素的方式存在问题,如下行

    userGroup.get('contacts.controls[i].controls.contact_name').touched
    

    这不会被控制解释为字符串。


    你需要像这样访问元素,所以你的代码应该是这样的

       userGroup.controls.contacts.controls[i].controls.contact_name.status
    

    因此,根据代码,您首先需要访问 from(userGroup),然后转到 controls and cotacts fromarray,并且由于 fromarray 是一组元素,通过索引 i 访问它,然后引用该数组中的单个元素 contact_name

    基于阅读本文的答案 : Angular 中的响应式表单:Dynamically Creating Form Fields With FormArray

    【讨论】:

    • 在这种情况下如何访问它?对于其他元素,它绝对可以正常工作。
    • @D555 - 您访问元素的方式,您可以在此处查看详细信息:alligator.io/angular/reactive-forms-formarray-dynamic-fields...
    • @D555 - 您也可以根据链接中给出的更易读的方式更改 html ..您也可以投票
    【解决方案2】:

    我不知道status 属性,但您绝对可以使用invalid 之一:

    userGroup.get('name').invalid
    

    【讨论】:

    • status 属性可用,我只在 formarray 中得到错误,而不是在简单的场景中
    • 我采用了“简单场景”,因为我不想写一个完整的行,但无论如何你都应该使用 invalid 属性,它就是为此而生的。
    【解决方案3】:

    而不是userGroup.get('address.city')

    您应该使用以下方式访问它:

    userGroup.get(userGroup.controls["address"].controls['city']).status.

    您将objectstring 混合在一起

    【讨论】:

    • 问题不在于 address.city 字段,问题在于联系人 -> contact_name,address.city 工作正常
    • 对它做同样的事情,从userGroup.get(contacts.controls[i].controls.contact_name).touched &amp;&amp; userGroup.get(contacts.controls[i].controls.contact_name).status中删除字符串引号
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多