Search code examples
angularangular4-formsngmodelangular-ngmodelchange

angular 4 template driven form - mark from one field secondone as touched


i have two fields f.e.

<form #f="ngForm" novalidate (ngSubmit)="save(f.value, f.valid)">
<div>
    <label>Name</label>
    <input type="text" name="name" [(ngModel)]="user.name" #name="ngModel" required minlength="5">
    <label>Street</label>
    <input type="text" name="street" [(ngModel)]="user.surname" #surname="ngModel" required>
</div>
<button type="submit">Submit</button></form>

i want to mark one of those fields from secondone as touched, it is possible? i tried to use (ngModelChange)="surname.control.markAsTouched(true)" on name to mark surname as touched but it doesnt work


Solution

  • (ngModelChange) will work when you change the first input value, you can use (blur) to mark the second touched when the first is.

    <input type="text" name="name" [(ngModel)]="user.name" #name="ngModel" 
      (ngModelChange)="surname.control.markAsTouched()" required minlength="5">
    <input type="text" name="street" [(ngModel)]="user.surname" #surname="ngModel" required>
    {{surname.touched | json}}
    <button type="submit">Submit</button>
    

    Demo Plunker