TypeError: Cannot read property 'valid' of undefined

后端 未结 5 492
执念已碎
执念已碎 2020-12-30 23:41

I have the following textarea:


相关标签:
5条回答
  • 2020-12-31 00:10

    In your case content is a property on your model.

    In order to do what you want you need to use a template reference value for the form control #myControl="ngModel" and then you have access to the valid property: myControl.valid.

    So in your example:

    <textarea class="form-control" [(ngModel)]="content"
              name="content" required #myControl="ngModel">
    </textarea>
    

    And use it in the button tag:

    <button type="submit" class="btn btn-default" 
    [disabled]="myControl.valid">New comment</button>
    
    0 讨论(0)
  • 2020-12-31 00:16
    <div class="form-group">
        <label for="inputEmail" class="col-lg-2 control-label">Email</label>
        <div class="col-lg-10">
            <input type="text" class="form-control" id="name" placeholder="Name" minlength="4" maxlength="24"  [(ngModel)]="name" name="email" #myName="ngModel" required>
                <div *ngIf="myName.errors && (myName.dirty || myName.touched)" class="alert alert-danger">
                    <div [hidden]="!myName.errors.required">
                        Name is required
                    </div>
                    <div [hidden]="!myName.errors.minlength">
                        Name must be at least 4 characters long.
                    </div>
                    <div [hidden]="!myName.errors.maxlength">
                        Name cannot be more than 24 characters long.
                    </div>
                </div>
        </div>
    </div>
    
    0 讨论(0)
  • 2020-12-31 00:17

    In my case i removed the ngModel from #myName="ngModel" to make it work. Angualr version 5.2.11

    0 讨论(0)
  • 2020-12-31 00:20

    I had this problem due to using ng-if. I solved it using ng-hide instead.

    ng-hide set DOM visibility false but ng-if removes DOM completely. Probably thats why angularjs can't see the form to validate when ng-if is used

    0 讨论(0)
  • 2020-12-31 00:35

    You could use ngModelChange as a workaround:

    <input type="text" [ngModel]="model.property (ngModelChange)="detectChanges($event, model, validation)" #validation="ngModel" required validation>
    

    And in your component:

     detectChanges(newVal, model, validation): void {
         if (validation.valid) model._valid = true;
         else model._valid = false;
     }
    

    This can give you more flexibility when you are using *ngFor to display lots of input fields and want to validate them individually.

    0 讨论(0)
提交回复
热议问题