嗨我是angular 2的新手,我在过去的一周中使用了angular 2,并想知道是否可以使用动态模板和动态样式生成动态组件。这意味着follwoing应该是这样的在Angular 2中创建一个动态组件
@Component({
// 2a
selector: 'dynamic placeholder',
// 2b
styles: [`dynamic styles`]
// 2c
template: `dynmic template`
})
是有可能做到这一点在角2,我记得这是这样,也许可能在角1
任何帮助将不胜感激(Escpecially plunkers用简单的代码)
这是我迄今取得:尝试使用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();
}
}
这里是一个plunker使创建动态组件,我不知道是否创建动态CSS是可能的,我会很高兴,如果一些我可以回答我的问题: http://plnkr.co/edit/ZXsIWykqKZi5r75VMtw2?p=preview
StackOverflow不是让你让人为你写代码的地方。向我们展示您的尝试并做出坚实的努力 –
好的我会以正确的方式上传它,代码甚至不会工作 – Brk
而不是试图关闭此线程,为什么不能互相帮助。我正在努力试图了解这个主题是否可能在角度2中。如果不是,我不会迁移到角度2或使用它。 我在互联网上传递了我的例子,对于我的案例没有确切的答案。 – Brk