[英]Create a Dynamic Component in Angular 2
嘿,我刚开始接触Angle 2,在过去一周中,我玩过Angle 2,想知道是否可以生成具有动态模板和动态样式的动态组件。 这意味着跟随应该像这样
@Component({
// 2a
selector: 'dynamic placeholder',
// 2b
styles: [`dynamic styles`]
// 2c
template: `dynmic template`
})
有可能在角度2中做到这一点,我记得在角度1中可能做到这一点
任何帮助将不胜感激(尤其是简单代码的小伙子们)
到目前为止,这是我已经实现的目标:尝试使用ComponentFactoryResolver:
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule {
}
@Component({
selector: 'my-app',
template: `
<div>Hello, world!</div>
`
})
export class AppComponent {
}
@NgModule({
declarations: [HomeComponent],
exports: [HomeComponent]
})
export class HomeModule {
}
@Component({
selector: 'home',
template: `
<div>This is home</div>
`
})
export class HomeComponent {
}
@Component({
selector: 'hello-world',
template: `
<div>
Hello, world!, {{name}}
The answer is: {{getAnswer()}}
</div>
`
})
export class HelloWorldComponent implements AfterViewInit {
private name:string = 'You';
constructor(private helloWorldService: HelloWorldService) {
}
ngAfterViewInit(): void {
this.name = 'Me';
}
private getAnswer() {
return this.helloWorldService.giveMeTheAnswer();
}
}
@NgModule({
declarations: [HomeComponent, HelloWorldComponent],
providers: [HelloWorldService],
exports: [HomeComponent]
})
export class HomeModule {
}
@Component({
selector: 'home',
template: `
<button (click)="sayHello()">Say hello</button>
<div>This is home</div>
`
})
export class HomeComponent {
constructor(private componentFactoryResolver: ComponentFactoryResolver,
private viewContainerRef: ViewContainerRef) {
}
private sayHello() {
const factory = this.componentFactoryResolver.resolveComponentFactory(HelloWorldComponent);
const ref = this.viewContainerRef.createComponent(factory);
ref.changeDetectorRef.detectChanges();
}
}
这是一个可以创建动态组件的插件,我不知道是否可以创建动态CSS,如果有人可以回答我的问题,我会感到很高兴: http ://plnkr.co/edit/ZXsIWykqKZi5r75VMtw2?p=preview
使用TypeScript和Angular2的最新版本(我相信该功能已在2.4.0中发布),您可以创建1个基本组件,然后对其进行扩展。 属性( @Input/@Output/@ViewChild
)上的所有装饰器/注释都将被复制。 但是,必须为每个祖先@Component
属性指定属性,即不能仅覆盖selector
,而不能覆盖所有内容。 那是正确的方法。
另一种方法->使用reflect-metadata
更新Component类上的装饰器(可能正是您要找的,因为那样的话您可以一次覆盖1个属性),但是请小心export
(即公开)所有Components /您要覆盖的组件内部使用的指令/服务。 例如,有些库具有多个组件,而有些则仅在内部使用(即,无法以正常方式将其导入到模块中……但是,您可以尝试使用providers
)。 例如,如果您尝试“覆盖”,则带reflect-metadata
css会使用内部组件-> angular / typescript将崩溃,因为它无法解析“内部”内容。 您可以从以下答案开始: StackOverflow
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.