简体   繁体   中英

How Validators work with change detection strategy “onPush” in Dart Angular?

My form component has change detection strategy onPush. I have a code in ngFor:

<div *ngFor="let externalLink of edited.externalLinks">
  <input #xctrl="ngForm" type="text" class="form-control" id="extId" required [(ngModel)]="externalLink.extId" ngControl="linkExtId_{{externalLink.id}}">

  Valid status is {{xctrl.control.valid}}
</div>

User add new row in list by clicking button.

void addExternalLink() {
  if (edited != null) {
    edited.externalLinks.add(ExternalLink()..id = Uuid().v4().toString());
    _cdr.markForCheck();
  }
}

Input has "required" directive. After new row appeared "Valid status is true", but input is empty. If user click on input and exit from control, validation status changed to false. Same effect if add two rows. First has status false and second true.

Why it work like this? Can you explain behaviors of validations when onPush strategy?

PS If I change template and delete ngControl="linkExtId_{{externalLink.id}}" then it work as expected. On new row I see "Valid status is false".

when you use template variable, it must be unique for each element. in your code:

   <div *ngFor="let externalLink of edited.externalLinks">
        <input #xctrl="ngForm" type="text" class="form-control" id="extId" required 
          [(ngModel)]="externalLink.extId" ngControl="linkExtId_{{externalLink.id}}">

        Valid status is {{xctrl.control.valid}}
   </div>

if you look at it, before you define template variable, you loop on the input element, and all the inputs that create, have the same template variable. because of that you could not validate each input separately. if you want to do that, you should use reactive form that makes dynamically. you can look at the document :

https://angular.io/guide/dynamic-form

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM