gpt4 book ai didi

Angular 2.0 最终 : How to instantiate a component from code

转载 作者:太空狗 更新时间:2023-10-29 17:12:28 25 4
gpt4 key购买 nike

我正在寻找一种从另一个组件的代码中实例化 Angular2 中的组件的方法。与许多提出类似问题的人不同,我对动态编译新组件不太感兴趣,只是实例化并插入应用程序中已经存在的组件。

例如:

假设我有两个组件:

dashboard-item.component.ts

import { Component } from "@angular/core";

@Component({
selector: "dashboard-item",
template: "Some dashboard item with functionality"
})
export class DashboardItemComponent {
constructor() {}

onInit() {}
}

dashboard.component.ts

import { Component } from "@angular/core";

@Component({
selector: "dashboard",
template: "<h1>Dashboard!</h1><div #placeholder></div>"
})
export class DashboardComponent {
constructor() {}

onInit() {}
}

我正在寻找的是一种在 DashboardComponent 的 onInit 中创建 DashboardItemComponent 并将其添加到 #placeholder div 的方法。

需要注意两点:

这两个较早的问题提出了类似的问题,但他们的答案要么相当乏味,要么与 Angular2 的早期(测试版)版本有关,而且似乎不再有效。

最佳答案

这是一个工作演示:https://plnkr.co/edit/pgkgYEwSwft3bLEW95Ta?p=preview

import {Component, NgModule, ViewChild, ElementRef, Input, Output, EventEmitter, ViewContainerRef, ComponentRef, ComponentFactoryResolver, ReflectiveInjector} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
selector: 'any-comp',
template: '<div (click)="clicked.emit($event)">here i am.. {{name}}</div>'
})
export class AnyComponent {

@Input() name;
@Output() clicked = new EventEmitter();

constructor() {
console.log('some1 created me.. ! :)');
}
}

@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<template #placeHolder>
</template>
</div>
`,
})
export class App {

@ViewChild('placeHolder', {read: ViewContainerRef}) private _placeHolder: ElementRef;

name:string;
constructor(private _cmpFctryRslvr: ComponentFactoryResolver) {
this.name = 'Angular2'
}

ngOnInit() {
let cmp = this.createComponent(this._placeHolder, AnyComponent);

// set inputs..
cmp.instance.name = 'peter';

// set outputs..
cmp.instance.clicked.subscribe(event => console.log(`clicked: ${event}`));

// all inputs/outputs set? add it to the DOM ..
this._placeHolder.insert(cmp.hostView);
}

public createComponent (vCref: ViewContainerRef, type: any): ComponentRef {

let factory = this._cmpFctryRslvr.resolveComponentFactory(type);

// vCref is needed cause of that injector..
let injector = ReflectiveInjector.fromResolvedProviders([], vCref.parentInjector);

// create component without adding it directly to the DOM
let comp = factory.create(injector);

return comp;
}
}

@NgModule({
imports: [ BrowserModule ],
declarations: [ App, AnyComponent ], // ! IMPORTANT
entryComponents: [ AnyComponent ], // ! IMPORTANT --> would be lost due to Treeshaking..
bootstrap: [ App ]
})
export class AppModule {}

关于 Angular 2.0 最终 : How to instantiate a component from code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39685125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com