0

I am currently working on a wrapper for the forms. Everthing works beside the validation.The problem is that my ngForm property does not contain the controls from the ng-content. The goal is that the ngSubmit EventEmitter only emits if the form is valid.

This is the current status:

import { Component, Input, ViewChild, Output, EventEmitter } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
 selector: 'px-form',
 template: `
   <form (ngSubmit)="f.form.valid && ngSubmit.emit($event)" #f="ngForm">
     <ng-content></ng-content>
   </form>
})
export class PxFormComponent {
  @ViewChild('f') ngForm: NgForm;
  @Output() ngSubmit = new EventEmitter();
}
alc
  • 97
  • 1
  • 1
  • 6

1 Answers1

0

You might find a solution to your problem in this post:

Q: How to use Angular 2 template form with ng-content?

Code taken from the post:

@Component({
  selector: 'my-custom-form',
  template: `
    <form (ngSubmit)="onSubmit(editForm)" #editForm="ngForm" novalidate>               
      <ng-content></ng-content>
      <button type="submit">Submit</button>
    </form>
  `,
})
export class MyCustomFormComponent implements AfterViewInit {
  @ContentChildren(NgModel) public models: QueryList<NgModel>;
  @ViewChild(NgForm) public form: NgForm;

  public ngAfterViewInit(): void {
    let ngContentModels = this.models.toArray();
    ngContentModels.forEach((model) => {
      this.form.addControl(model);
    });
  }

  public onSubmit(editForm: any): void {
    console.log(editForm);
  }
}
Grégory Elhaimer
  • 2,731
  • 1
  • 16
  • 21