Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Template Driven nested form validation?

Tags:

angular

I have 2 components, a parent component and a child component. The parent component contains the following:

   <form (ngSubmit)="saveWebsite();" #adminForm="ngForm">

         <input type="text" name="WebName" [(ngModel)]="milestone.WebName" class="form-control" required/>

          <app-documents [documents]="caseData.CaseWebsiteDocuments" [caseId]="caseId" (fileEvent)="showToast($event)"
          (documentsEvent)="documentsEvent($event)"></app-documents>

      <button type="submit" class="btn btn-success pull-right" *ngIf="caseId">Save</button>
    </form>

The child component contains the following:

<input  type="text" [(ngModel)]="doc.FriendlyName" name="friendlyName" class="form-control" required/>

If I put all inputs in the parent component, the validation works for everything. I am trying to check the dirty status. Right now, if I make changes on the Parent, the dirty status is set to true, but if I make a change on the child, the dirty status does not change. How can I get validation to work in template driven nested controls?

like image 848
xaisoft Avatar asked Dec 10 '22 09:12

xaisoft


2 Answers

You can provide ControlContainer on your child component like

import { ControlContainer, NgForm } from '@angular/forms';

@Component({
  selector: 'app-documents'
  ...,
  viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})
export class AppDocumentsComponent {}

See also

  • Angular2 nested template driven form
like image 92
yurzui Avatar answered Dec 12 '22 23:12

yurzui


That alone didn't work for me I added ngModel in my input too. Without ngModel I think you can't validate your forms... whether it is a child or own component forms.

import { ControlContainer, NgForm } from '@angular/forms';

@Component({
  selector: 'app-documents'
  ...,
  viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})
export class AppDocumentsComponent {}

that works for me!!

like image 42
siddharth bhardwaj Avatar answered Dec 12 '22 22:12

siddharth bhardwaj