Angular 4 Access multiple templates (ng-template) in dynamic form

I am following the https://angular.io/docs/ts/latest/cookbook/dynamic-form.html guide for implementing dynamic forms.

Now I have a dynamic form component that takes a FormModel and a form group as input:

mycomponent.html

<dynamic-form [form]="form"
              [formModel]="formModel">
</dynamic-form>

      

My dynamic form component goes through a formModel component and a render df-control that renders a specific control based on the settings defined for that control in the form model:

dynamic form.component.html

<form [formGroup]="form" (ngSubmit)="onSubmitForm()">

    <div *ngFor="let controlModel of formModel" class="form-row">
        <df-control [controlModel]="controlModel" [form]="form" [formModel]="formModel">
        </df-control>
    </div>

    <div class="form-group">
        <button type="submit">Save</button>
        <button type="button" (click)="onCancel()">Cancel</button>
    </div>
</form>

      

For some form fields defined in my FormModel, I don't want this to be displayed via df-control. Instead, I want to be able to specify templates for such controls between dynamic form tags. And want the corresponding template to be displayed when passing through the formModel

For example, if I have a form with 6 fields:

<dynamic-form [form]="form" [formModel]="formModel">
    <template [modelId]="'field3'">
        <p>my custom template for field 3</p>
    </template>
    <template [modelId]="'field5'">
        <p>my custom template for field 5</p>
    </template>
</dynamic-form>

      

I want all fields to display normally, excluding field3 and field5. For field3 and field5, I don't want to render df-control, but instead I want the corresponding template to be displayed

i.e. for field 3:

<template [modelId]="'field3'">
     <p>my custom template for field 3</p>
</template>

      

and for field 5:

<template [modelId]="'field5'">
     <p>my custom template for field 5</p>
</template>

      

Can anyone explain how to achieve this?

I found this, similar to what I am looking for, but not very clear.

Stackoverflow question

Any help would be really appreciated.

+3


source to share





All Articles