Angular 13 指令 viewContainerRef.createComponent 将对象传递给创建的组件
Angular 13 Directive viewContainerRef.createComponent pass object to created component
下面的代码在 Angular 13
中动态创建一个组件
指令:
import { Directive, Input, ViewContainerRef, Type } from '@angular/core';
@Directive({
selector: '[appLoader]'
})
export class LoaderDirective {
@Input() appLoader!: Type<any>;
constructor(private viewContainerRef: ViewContainerRef) {}
ngOnInit(): void {
this.viewContainerRef.createComponent(this.appLoader);
}
}
app.component.html
<div [appLoader]="component"></div>
app.component.ts
component = MyComponent
我还需要将一个对象传递到创建的组件中,这是创建的组件将使用的一些额外信息。
我该怎么做?
我想你的指令可能有点像
export class LoaderDirective {
@Input() appLoader!: Type<any>;
@Input() arg:any; //<--you pass as arg any object
//you need inject ComponentFactoryResolver
constructor(private viewContainerRef: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver) {}
ngOnInit(): void {
//first you "create" a component
const component=this.componentFactoryResolver.resolveComponentFactory(this.appLoader)
//in componentRef you get a instance of the component
const componentRef=this.viewContainerRef.createComponent(component);
//you can access to the component using componentRef.instance
//e.g. componentRef.instance.someMethod()
// componentRef.instance.prop="what-ever"
//I choose use the object pass in the "arg" Input
Object.keys(this.arg).forEach(x=>{
componentRef.instance[x]=this.arg[x]
})
}
你喜欢
<div [appLoader]="component" [arg]="{name:'Angular'}"></div>
看到一个fool stackblitz
下面的代码在 Angular 13
中动态创建一个组件指令:
import { Directive, Input, ViewContainerRef, Type } from '@angular/core';
@Directive({
selector: '[appLoader]'
})
export class LoaderDirective {
@Input() appLoader!: Type<any>;
constructor(private viewContainerRef: ViewContainerRef) {}
ngOnInit(): void {
this.viewContainerRef.createComponent(this.appLoader);
}
}
app.component.html
<div [appLoader]="component"></div>
app.component.ts
component = MyComponent
我还需要将一个对象传递到创建的组件中,这是创建的组件将使用的一些额外信息。
我该怎么做?
我想你的指令可能有点像
export class LoaderDirective {
@Input() appLoader!: Type<any>;
@Input() arg:any; //<--you pass as arg any object
//you need inject ComponentFactoryResolver
constructor(private viewContainerRef: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver) {}
ngOnInit(): void {
//first you "create" a component
const component=this.componentFactoryResolver.resolveComponentFactory(this.appLoader)
//in componentRef you get a instance of the component
const componentRef=this.viewContainerRef.createComponent(component);
//you can access to the component using componentRef.instance
//e.g. componentRef.instance.someMethod()
// componentRef.instance.prop="what-ever"
//I choose use the object pass in the "arg" Input
Object.keys(this.arg).forEach(x=>{
componentRef.instance[x]=this.arg[x]
})
}
你喜欢
<div [appLoader]="component" [arg]="{name:'Angular'}"></div>
看到一个fool stackblitz