Create a gist now

Instantly share code, notes, and snippets.

@ryotah /container.ts
Last active Oct 22, 2017

Embed
What would you like to do?
templateを動的に外部から読み込んで表示させる #angular
/**
* 利用側
*/
import { AfterViewInit, Component, ViewChild, ViewContainerRef } from '@angular/core';
import { TemplateStorageComponent } from '../../../../shared/components/template-storage/template-storage.component';
import { logger } from '../../../../shared/utils/logger/index';
@Component({
selector: 'app-container',
template: `
<div>
<ng-container #anchor></ng-container>
</div>
<app-template-storage></app-template-storage>
`,
})
export class ContainerComponent implements AfterViewInit {
@ViewChild('anchor', { read: ViewContainerRef }) private anchor: ViewContainerRef;
@ViewChild(TemplateStorageComponent) private templateStorage: TemplateStorageComponent;
constructor() { }
ngAfterViewInit() {
for (const template of this.templateStorage.templates.toArray()) {
logger.info(template.name);
this.anchor.createEmbeddedView(template.templateRef);
}
}
}
import { ChangeDetectionStrategy, Component, QueryList, TemplateRef, ViewChild, ViewChildren } from '@angular/core';
import { TemplateNameDirective } from '../../directives/template-name.directive';
@Component({
selector: 'app-template-storage',
template: `
<ng-template appTemplateName="foo">foo</ng-template>
<ng-template appTemplateName="bar">bar</ng-template>
<ng-template #foo>foo</ng-template>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class TemplateStorageComponent {
@ViewChildren(TemplateNameDirective) templates: QueryList<TemplateNameDirective>;
// `appTemplateName`のようなDirectiveを利用しない場合
@ViewChild('foo') foo: TemplateRef<any>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment