【问题标题】:Inserting Inputs in Dynamically imported Components in Angular在 Angular 中动态导入的组件中插入输入
【发布时间】:2020-03-08 01:38:10
【问题描述】:

我有一个函数用于将组件从 Angular 核心应用程序导入到所有库。 此函数将组件作为 dom 元素返回,我将其附加到子库中。 现在我想获取组件,但同时给它一些输入。

这是我正在使用的代码。我没有收到任何错误,但没有看到输入属性。

将组件作为 dom 元素返回的函数

getComponent(componentInput?: string): HTMLElement {

const componentFactory = this.componentFactoryResolver.resolveComponentFactory(SharedcomponentComponent); 
const componentRef = componentFactory.create(this.injector);

//Injecting Inputs to the component instance
if(componentInput != undefined){
   componentRef.instance.someProp = componentInput;
}

this.appRef.attachView(componentRef.hostView);

const domElem = (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
return domElem;
}

我的组件

@Component({
selector: 'app-sharedcomponent',
templateUrl: './sharedcomponent.component.html',
styleUrls: ['./sharedcomponent.component.css']
})


export class SharedcomponentComponent implements OnInit {

@Input('someProp') someProp: string;
constructor() { }
ngOnInit() {

}

clickMe(){
  alert("I am the core component :)");
}

}

我的组件 Html

<button (click)="clickMe()">
  Click Me :)
</button>
<br/>
<p>
  Hello there {{someProp}}
</p>

【问题讨论】:

    标签: angular input components


    【解决方案1】:

    我找到了解决方案。 下面的代码现在可以正常工作了

    getComponent(componentInput?: string): HTMLElement {
    
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(SharedcomponentComponent); 
    const componentRef = componentFactory.create(this.injector);
    
    //Injecting Inputs to the component instance
    if(componentInput != undefined){
      let inputs = { someProp: componentInput };
    
      Object.keys(inputs).map(input => {
        componentRef.instance[input] = inputs[input];
      });
    }
    
    this.appRef.attachView(componentRef.hostView);
    const domElem = (componentRef.hostView as EmbeddedViewRef<SharedcomponentComponent>).rootNodes[0] as HTMLElement;
    return domElem;
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-06
      • 2017-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多