繁体   English   中英

Angular Ivy,文本节点如何指向其 ng-template

[英]Angular Ivy, how a text node points to its ng-template

我需要在测试中找到tpl1的文本节点在渲染后属于ng-template

1
<ng-template tpl>
  tpl1
</ng-template>
2

如果要在渲染后找到 tpl1 的tpl1 ,那么它的父级指向component的节点,但我想确保 tpl1 的tpl1派生自ng-template

到目前为止,我能够经典模式下做到这一点,但在ivy找不到这样做的方法。

下面有一个最小示例,任何解决方案(不仅使用 elDef 和 tNode)都对我有用。

import {Component, DebugNode, Directive, TemplateRef, VERSION, ViewChild, ViewContainerRef} from '@angular/core';
import {TestBed} from "@angular/core/testing";

@Directive({
  selector: '[tpl]',
})
class TplDirective {
  public constructor(public readonly tpl: TemplateRef<any>) {}
}

@Component({
  selector: 'target',
  template: `
    1
    <ng-template tpl>
      tpl1
    </ng-template>
    2
  `,
})
class TargetComponent {
  @ViewChild(TplDirective, {
    read: TemplateRef,
  }) public readonly tpl?: TemplateRef<any>;
  @ViewChild(TplDirective, {
    read: ViewContainerRef,
  }) public readonly vcr?: ViewContainerRef;
}

describe('issue-289', () => {
  beforeEach(() => TestBed.configureTestingModule({
    declarations: [TplDirective, TargetComponent],
  }).compileComponents());

  fit('finds right parent in ivy', () => {
    const fixture = TestBed.createComponent(TargetComponent);
    fixture.detectChanges();
    const componentEl = fixture.debugElement;
    const component: TargetComponent = componentEl.componentInstance;

    // check that only defaults have been rendered
    expect (componentEl.childNodes.length).toEqual(3);
    const [txtEl1, tplEl, txtEl2] = componentEl.childNodes;
    expect(txtEl1.nativeNode.nodeName).toEqual('#text');
    expect(tplEl.nativeNode.nodeName).toEqual('#comment');
    expect(txtEl2.nativeNode.nodeName).toEqual('#text');

    // rendering the template
    component.vcr.createEmbeddedView(component.tpl);
    fixture.detectChanges();

    // looking for the new element
    expect (componentEl.childNodes.length).toEqual(4);
    const txtTplEl = componentEl.childNodes.find(el => el !== txtEl1 && el !== tplEl && el !== txtEl2);
    expect(txtTplEl.nativeNode.nodeName).toEqual('#text');

    // getting internal node, 1st is classic, 2nd is ivy
    const tplElNode = (tplEl.injector as any).elDef || (tplEl.injector as any)._tNode;
    expect(tplElNode).toBeDefined();

    // FIXME find how txtTplEl points to tplEl
    // in classic (not ivy) it works like that
    const txtTplNode = (txtTplEl as any)._debugContext?.view?.parentNodeDef;

    // should succeed
    expect(txtTplNode).toEqual(tplElNode);
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM