html 如何创建组合多个模板的Angular 指令?

cyvaqqii  于 2022-11-20  发布在  Angular
关注(0)|答案(1)|浏览(125)

bounty将在4天后过期。回答此问题可获得+100声望奖励。Jeff希望吸引更多人关注此问题。

我正在尝试创建一个自定义指令,它将允许我从json / ts对象读取模板,并将其插入到我的指令模板中。
例如,在配置文件/ database / ts文件中,我有:

{
//...
  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

我想从配置文件中获取文本(html),用程序员传递的模板替换<AD_GROUPS>标记,然后将其呈现到页面中。

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

我已经创建了指令:

@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);
  }
}

console.log生成的HTML:

<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>

个问题

1.如何将adListDivRef附加到正确的父对象上?我想我可以这样访问父对象:this.renderer.parentNode(this.vcr.element.nativeElement)

  1. mat-list似乎找不到我内嵌的*ngFor的清单项目。我该如何找到它?我在想,也许我的指令先被呼叫,而下一个指令没有被呼叫?
    用最少的代码实现Stackblitz:https://stackblitz.com/edit/angular-ivy-zv16cn
idv4meu8

idv4meu81#

以下是实现目标的两个步骤:
1.将生成的ag-group-text元素放入页面

this.vcr.element.nativeElement.parentNode.appendChild(groupListDivElement);

1.将正确的context传递到动态生成的模板中

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

**注意:**使用ViewContainerRef.createEmbeddedTemplate(templateRef)可以确保您不需要担心渲染模板中的变化检测,因为变化检测器成为Angular 变化检测树的一部分。如果是templateRef.create,您必须自己处理变化检测


相关问题