angular 绕弯实现 react 动态组件传值解构透传方法

实现:hoc.component.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { AfterViewInit, Component, Input, Type, ViewChild, ViewContainerRef } from '@angular/core';

@Component({
selector: 'app-hoc',
template: ` <ng-template #hoc />`,
})
export class HocComponent implements AfterViewInit {
@ViewChild('hoc', { read: ViewContainerRef })
private container!: ViewContainerRef;
@Input()
component: Type<Component> | undefined;
@Input()
options: unknown;

ngAfterViewInit(): void {
if (this.component === undefined) {
throw new Error('this.component can not be undefined');
}
const ref = this.container.createComponent(this.component);
if (!this.options) return;
Object.assign(ref.instance, this.options);
ref.changeDetectorRef.detectChanges();
}
}

用法:home.component.html

1
<app-hoc [component]="component" [options]="options" />