1
votes

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?

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

1
could you please explain your exact problem? your explanation is really vague! - Seyed-Amir-Mehrizi
The valid property of control not changed. After create row I see "Valid status is true". But it should be false. Valid status changed after form clicking, but data not changed and validate method not executed. - Cododoc

1 Answers

0
votes

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