# ng-japan OnAir #49 ViewContainerRefを再発見 ``` ng-japan OnAirはAngular日本ユーザー会が主催するオンラインイベントです https://community.angular.jp connpass: https://connpass.com/event/231619 shownote: https://hackmd.io/@lacolaco/Bk4d_hX_F #Angular #ng_jp_onair ``` ## アジェンダ ### ViewContainerRefの概要 [ViewContainerRef](https://angular.jp/api/core/ViewContainerRef#createComponent) > Represents a container where one or more views can be attached to a component. ```typescript @Component({...}) class SomeComponent { constructor(private vcRef: ViewContainerRef) {} loadDynamicComponent() { this.vcRef.createComponent(OtherComponent); } } ``` https://stackblitz.com/edit/angular-ivy-vcqcl8?file=src/app/app.component.ts ### API #### [createComponent\(\)](https://angular.jp/api/core/ViewContainerRef#createcomponent) ```typescript abstract createComponent<C>( componentType: Type<C>, options?: { index?: number; injector?: Injector; ngModuleRef?: NgModuleRef<unknown>; projectableNodes?: Node[][]; } ): ComponentRef<C> ``` ### [createEmbeddedView\(\)](https://angular.jp/api/core/ViewContainerRef#createembeddedview) ```typescript abstract createEmbeddedView<C>( templateRef: TemplateRef<C>, context?: C, index?: number ): EmbeddedViewRef<C> ``` ### ViewContainerRefの場所 ![](https://i.imgur.com/9MSMbFb.png) ### ソースコードを読む [angular/view\_container\_ref\.ts at master · angular/angular](https://github.com/angular/angular/blob/master/packages/core/src/linker/view_container_ref.ts#L51) [RouterOutletから学ぶViewContainerRef](https://github.com/angular/angular/blob/master/packages/router/src/directives/router_outlet.ts) ### 遅延読み込みコンポーネント(SCAMパターン) [Emulating tree\-shakable components using single component Angular modules \- DEV Community](https://dev.to/this-is-angular/emulating-tree-shakable-components-using-single-component-angular-modules-13do) ```typescript @Component({ selector: 'app-lazy', template: `<p>lazy works!</p>`, styleUrls: ['./lazy.component.css'], }) export class LazyComponent implements OnInit { constructor() {} ngOnInit() {} } @NgModule({ declarations: [LazyComponent], imports: [CommonModule], }) export class LazyComponentModule {} ``` ```typescript async loadLazyComponent() { const LazyComponent = await import('./lazy/lazy.component').then( (m) => m.LazyComponent ); const factory = this.cfr.resolveComponentFactory(LazyComponent); const component = this.vcRef.createComponent(factory); } ``` ###### tags: `ng_jp_onair`