Jeff
Jeff

Reputation: 4433

How to create an Angular directive that combines multiple templates?

I am trying to create a custom directive that will allow me to read a template from a json / ts object and insert it in my directive template.

For example, in a config file / database / ts file, I have:

{
//...
  text: '<p>Many of our tools ...AD Groups:</p><AD_GROUPS id="AD_GROUPS"></AD_GROUPS><p>To request access, ...',
  AD_GROUPS: [
    'my-team-users'
  ],
//...
} // truncated and wrapped for readability

I want to take the text(html) from the config file, replace the <AD_GROUPS> tag with the template the programmer passes in, and render it to the page. The directive is consumed like this:

<div *appAdGroupText="cfg">
  <mat-list>
    <mat-list-item *ngFor="let group of cfg.AD_GROUPS">{{group}}</mat-list-item>
  </mat-list>
</div>

I have created the directive:

@Directive({selector: '[appAdGroupText]'})
export class AdGroupTextDirective implements OnChanges {

  _config: ConfigurationItemModel | undefined;

  constructor(
    private templateRef: TemplateRef<unknown>,
    private vcr: ViewContainerRef,
    private renderer: Renderer2
    // private resolver: ComponentFactoryResolver
  ) {
  }

  @Input() set appAdGroupText(cfg: ConfigurationItemModel) {
    this._config = cfg;
    this.render();
  }

  render() {
    const cfg = this._config; // config is set in a set method. This has the correct value
    const groupListDivElement: HTMLDivElement = this.renderer.createElement('my-group-text'); // creates a 'parent' element
    groupListDivElement.innerHTML = cfg.text; // set the inner html to the config text
    const adListDivRef = this.templateRef.createEmbeddedView(null); // create an unattached version of the template

    // loop through, and replace the "AD_GROUPS" custom tag with the generated template
    groupListDivElement.childNodes.forEach(n => {
    if (n.nodeName === 'AD_GROUPS') {
      n.replaceWith(adListDivRef.rootNodes[0]); // this is incorrect. I only get the root node, rather than the entire node with its children
    }
    // arguably, the above could be replaced with an Array.from(...) find / replace
    console.log(groupListDivElement); // SEE HTML OUTPUT
    // How do I render groupListDivElement in the VCR / renderer???


      // this works will put the mat-list ONLYin:
      // let view = this.templateRef.createEmbeddedView(null);
      // this.vcr.insert(view);
  }
}

Generated HTML from the console.log:

<my-group-text _ngcontent-hwh-c107="">
<p>Many of our tools are restricted to specific groups in Active Directory. In order to access the required tools, you will need access to the following AD Groups:</p>
<div _ngcontent-hwh-c107="">
   <mat-list _ngcontent-hwh-c107="" class="mat-list mat-list-base">
      <!--container-->
   </mat-list>
</div>
<p>
   To request access, <a href="https://access" target="_blank" rel="noopener noreferrer">click here</a> and fill out the form with the following information:
   <ad_form_table></ad_form_table>
</p>
<p>You will need to create a ticket for each of the above groups listed.</p>
</ad-group-text>

Issues

  1. How do I get adListDivRef appended to the proper parent? I think I can access the parent thusly: this.renderer.parentNode(this.vcr.element.nativeElement)?
  2. The mat-list does not seem to find the list items from my embedded *ngFor. How do I get that? I am thinking maybe my directive is called first and the next one is not called?

Stackblitz with minimal code: https://stackblitz.com/edit/angular-ivy-zv16cn

Upvotes: 2

Views: 448

Answers (1)

yurzui
yurzui

Reputation: 214175

Here are two steps to achieve your goal:

  1. Put generated ag-group-text element into page

    this.vcr.element.nativeElement.parentNode.appendChild(groupListDivElement);
    
  2. Pass proper context into dynamically generated template

    const adListDivRef: EmbeddedViewRef<any> = 
        this.vcr.createEmbeddedView(this.templateRef, { cfg });
    

Note: using ViewContainerRef.createEmbeddedTemplate(templateRef) makes sure that you don't need to worry about change detection in rendered template because change detector becomes a part of Angular change detection tree. In case of templateRef.create you have to handle change detection by yourself

Forked Stackblitz

Upvotes: 1

Related Questions