Home > Net >  Usage - ngForm with ng-content
Usage - ngForm with ng-content

Time:11-09

I would like to create component like this:

<form #form="ngForm">
    <ng-content></ng-content>
</form>

But if I check the validation of this form, it's always true ({{ form.valid }}).

From the parrent component it looks like:

<app-form-component>
    <input [(ngModel)]="variable" required minlength="3">
</app-form-component>

I think that i should provide some thinks in FormComponent, but idk what. I tried to add:

providers: [{ provide: ControlContainer, useClass: NgForm }],

but It does't worked.

I expect to find way to correct validation my form.

CodePudding user response:

What you're doing is just recreating the ReactiveFormsModule. Stop using template driven forms, use reactive forms, you'll get what you're asking for.

<form novalidate [formGroup]="form">
  <input formControlName="username" type="text">
</form>
form = this.fb.group({
  username: ['', [Validators.required, Validators.minLength(3)]]
});

constructor(private fb: FormBuilder) {}

CodePudding user response:

I believe the problem is that content is intialized before the view (because it is actually the part of parent's template), and therefore controls don't find the form itself in their injector tree.

You could do something tricky like put ngIf in the parent's template that is false initially, and switches to true in setTimeout, or pass <ng-template> instead of actual template to app-form-component and render it when the view is initialized. But I would better try to put both the form and its content into one component

  • Related