依條件載入元件,實現元件的靈活切換,減少大量ngIf的使用,在angular中也是比較常見的操作。這篇文章就來大家一起交流angular元件的動態使用。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有幫助。
在加入元件之前,先定義一個錨點來告訴Angular 要把元件插入到什麼地方。
在src/dynamic-banner/ad.directive.ts下
import { Directive, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[ad-host]', }) export class AdDirective { constructor(public viewContainerRef: ViewContainerRef) { } }
AdDirective 注入了 ViewContainerRef 來取得容器視圖的存取權,這個容器就是那些動態加入的元件的宿主。
在 @Directive 裝飾器中,要注意選擇器的名稱:ad-host,它就是你將應用到元素上的指令。
相關推薦:《angular教學》
src/dynamic-banner/ad-banner.component.html
<div> <h3>Advertisements</h3> <ng-template></ng-template> </div>
import { Component, Input, OnInit, ViewChild, ComponentFactoryResolver, OnDestroy, SimpleChanges } from '@angular/core'; import { AdDirective } from './ad.directive'; import { AdItem } from './ad-item'; import { AdComponent } from './ad.component'; import { componentMap } from './component/utils'; @Component({ selector: 'app-ad-banner', templateUrl: './ad-banner.component.html', // styleUrls: ['./ad-banner.component.css'] }) export class AdBannerComponent implements OnInit { @Input() type: string = 'ad1' // 传入的key,确定加载那个组件 @Input() data: any = {} // 传入组件的数据 @ViewChild(AdDirective, {static: true}) adHost: AdDirective; // 动态组件的指令 constructor(private componentFactoryResolver: ComponentFactoryResolver) { } ngOnInit() { this.loadComponent(); } ngOnChanges(changes: SimpleChanges): void { if (changes['type']) this.loadComponent() } loadComponent() { // adItem 要加载的组件类,以及绑定到该组件上的任意数据 const adItem = new AdItem(componentMap[this.type], this.data) const componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component); const viewContainerRef = this.adHost.viewContainerRef; viewContainerRef.clear(); const componentRef = viewContainerRef.createComponent(componentFactory); (<adcomponent>componentRef.instance).data = adItem.data; } }</adcomponent>
import { Type } from '@angular/core'; export class AdItem { constructor(public component: Type<any>, public data: any) {} }</any>
import { Type } from '@angular/core'; export interface AdComponent { data: any; }
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { componets } from './component/utils'; import { AdDirective } from './ad.directive'; import { AdBannerComponent } from './ad-banner.component'; @NgModule({ imports: [ CommonModule ], exports:[ [...componets], AdDirective, AdBannerComponent, ], declarations: [ [...componets], AdDirective, AdBannerComponent, ], entryComponents: [ [...componets] ] }) export class ShareModule { }
import { HeroProfileComponent } from "./hero-profile.component"; import { HeroJobAdComponent } from './hero-job-ad.component'; const componentMap = { ad1: HeroProfileComponent, ad2: HeroJobAdComponent } const componets = [ HeroProfileComponent, HeroJobAdComponent ] export {componets, componentMap}
程式設計影片! !
以上是淺談angular9中元件動態載入的實作方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!