在Angular中渲染组件实例?

时间:2020-03-04 14:11:55

标签: angular dynamic

我已经手动创建了一个类的实例。此类具有@Component({ template: `hello {{ who }}` }) class Greeting { constructor (public who: string) { } } @Component({ template: `<ng-somehow-render [instance]="greeting"/>` }) class OtherComponent { public greeting: Greeting constructor () { this.greeting = new Greeting('world') } } 装饰器。如何呈现其模板?

ComponentFactoryResolver
  • ngComponentOutlet将给我该组件的一个实例。我已经有该实例,并且想要渲染它。
  • data_dict_list = [ { "Car": "8", "Destination": "Vienna", "DestinationCode": "K08", "DestinationName": "Vienna/Fairfax-GMU", "Group": "2", "Line": "OR", "LocationCode": "D1", "LocationName": "Town", "Min": "14" }, { "Car": "8", "Destination": "NewCrltn", "DestinationCode": "D13", "DestinationName": "New Carrollton", "Group": "1", "Line": "OR", "LocationCode": "D1", "LocationName": "Town", "Min": "12" }, { "Car": "6", "Destination": "Vienna", "DestinationCode": "K08", "DestinationName": "Vienna/Fairfax-GMU", "Group": "2", "Line": "OR", "LocationCode": "D1", "LocationName": "Town", "Min": "BRD" } ] for data_dict in data_dict_list: if data_dict['DestinationCode'] == "K08": if data_dict['Min'] not in ("", "ARR", "BRD"): if 10 < int(data_dict['Min']) < 20: print("") 将在内部创建实例。这样我的实例就没用了。

1 个答案:

答案 0 :(得分:1)

看起来您需要一个中间件组件来呈现其他组件的实例。

可能是这个

@Component({
    selector: 'ng-somehow-render',
    template: '',
})
export class NgSomehowRenderComponent implements OnInit {
    @Input() instance: any;

    constructor (
        private cfr: ComponentFactoryResolver,
        private vcr: ViewContainerRef,
        private cdr: ChangeDetectorRef,
    ) {
    }

    public ngOnInit(): void {
        const componentFactory = this.cfr.resolveComponentFactory(this.instance.constructor);

        this.vcr.clear();
        const componentRef = this.vcr.createComponent(componentFactory);
        for (const key of Object.getOwnPropertyNames(this.instance)) {
            componentRef.instance[key] = this.instance[key];
        }
        this.cdr.detectChanges();
    }
}

只需将其声明添加到模块中即可。

顺便说一下,Greeting组件应该在entryComponents的模块中声明。

@NgModule({
  declarations: [AppComponent, Greeting, NgSomehowRenderComponent],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent],
  entryComponents: [Greeting]
})

因为Angular会尝试解决构造函数的依赖性,所以您需要在其中添加@Optional()装饰器。

@Component({
  template: `hello {{ who }}`
})
export class Greeting {
  constructor(@Optional() public who: string) {}
}

利润。

您可以在此处查看实时演示:https://codesandbox.io/s/jolly-villani-32m5w?file=/src/app/app.component.ts

官方文档中的所有内容,因此您可以毫无问题地使用它:https://angular.io/guide/dynamic-component-loader#resolving-components

相关问题