user3529850
user3529850

Reputation: 976

ReactiveForm with ng-template

I have a "base" component that contains a form. Inside that form there are two form controls I would like not to define inside but use ng-container along *ngTemplateOutlet instead. When I do that, I am getting an error: formGroup expects a FormGroup instance.. The message is correct as the form control must exists inside a form group. I thought hat I could pass context via ngTemplateOutletContext and solve the issue, but it just does not work. To visualize what I am doing:

For the "base" component:

selector: 'app-component-a',

carFormGroup: FormGroup = this.fb.group({
	type: [''],
	model: [''],
	color: [''],
	country: [''],
	revenue: ['']
});

constructor(private fb: FormBuilder) {
}
<form [formGroup]="carFormGroup" (ngSubmit)="save()">
	<div id="grid-cell-car-manufacturer-details">
	<ng-container
	  [ngTemplateOutlet]="carDetailsTemplate"
	  [ngTemplateOutletContext]="{carFormGroup: carFormGroup}"></ng-container>
	</div>
</form>

and the template for the second component (using the base one):

<ng-template #bComponentOwnTemplate let-carFormGroup>
	<form [formGroup]="carFormGroup">
		<ul class="manufacturer-details">
		  <li><input type="text" formControlName="country"></li>
		  <li><input type="text" formControlName="revenue"></li>
		</ul>
	</form>
</ng-template>

<app-component-a
[carFormGroup]="bComponentOwnTemplate"></app-component-a>

But it does not work, still getting formGroup expects a FormGroup instance.. Is what I am trying to do even possible ? Can I have a form in "base" component and define some of its controls via ng-template in another component ?

Upvotes: 0

Views: 705

Answers (1)

Jo&#227;o Ghignatti
Jo&#227;o Ghignatti

Reputation: 2391

you defined your context as

{carFormGroup: carFormGroup}

and you're trying to access it inside your ng-template with

let-carFormGroup

For what I've done with ngTemplateOutletContext I'd either change to

let-carFormGroup="carFormGroup"

or change the context to

{$implicit: carFormGroup}

so I could use plain let-carFormGroup to access it.

Glad I could help.

Upvotes: 2

Related Questions