fix(docs-infra): clear unneeded DOM nodes in `CodeExample/TabsComponent` (#40802)

Both `CodeExampleComponent` and `CodeTabsComponent` components receive
some code via content projection, grab the projected content and pass it
through to a `CodeComponent` instance for formatting and displaying.

Previously, the projected content was kept in the DOM (hidden). This
unnecessarily increased the number of DOM nodes.

This commit fixes this by clearing the projected DOM nodes once their
content has been captured.

PR Close #40802
This commit is contained in:
George Kalpakas 2021-02-13 16:01:54 +02:00 committed by Joey Perrott
parent 7fa881919b
commit 8f7fea4ad8
4 changed files with 15 additions and 3 deletions

View File

@ -36,6 +36,10 @@ describe('CodeExampleComponent', () => {
expect(codeExampleComponent.aioCode.code.trim()).toBe(`const foo = "bar";`);
});
it('should clean-up the projected code snippet once captured', () => {
expect(codeExampleComponent.content.nativeElement.innerHTML).toBe('');
});
it('should change aio-code classes based on header presence', () => {
expect(codeExampleComponent.header).toBe('Great Example');
expect(fixture.nativeElement.querySelector('header')).toBeTruthy();

View File

@ -79,11 +79,13 @@ export class CodeExampleComponent implements AfterViewInit {
@HostBinding('class.avoidFile') isAvoid = false;
@ViewChild('content', { static: true }) content: ElementRef;
@ViewChild('content', { static: true }) content: ElementRef<HTMLDivElement>;
@ViewChild(CodeComponent, { static: true }) aioCode: CodeComponent;
ngAfterViewInit() {
this.aioCode.code = this.content.nativeElement.innerHTML;
const contentElem = this.content.nativeElement;
this.aioCode.code = contentElem.innerHTML;
contentElem.innerHTML = ''; // Remove DOM nodes that are no longer needed.
}
}

View File

@ -70,6 +70,10 @@ describe('CodeTabsComponent', () => {
const codeContent = fixture.nativeElement.querySelector('aio-code').textContent;
expect(codeContent.indexOf('Code example 1') !== -1).toBeTruthy();
});
it('should clean-up the projected tabs content once captured', () => {
expect(codeTabsComponent.content.nativeElement.innerHTML).toBe('');
});
});
@Component({

View File

@ -55,7 +55,9 @@ export class CodeTabsComponent implements OnInit, AfterViewInit {
ngOnInit() {
this.tabs = [];
const codeExamples = Array.from(this.content.nativeElement.querySelectorAll('code-pane'));
const contentElem = this.content.nativeElement;
const codeExamples = Array.from(contentElem.querySelectorAll('code-pane'));
contentElem.innerHTML = ''; // Remove DOM nodes that are no longer needed.
for (const tabContent of codeExamples) {
this.tabs.push(this.getTabInfo(tabContent));