【发布时间】:2017-07-07 12:22:54
【问题描述】:
嘿,我是 angular 2 的新手,过去一周我一直在玩 angular 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();
}
}
这是一个可以创建动态组件的 plunker,我不知道是否可以创建动态 css,如果有人能回答我的问题,我会很高兴: http://plnkr.co/edit/ZXsIWykqKZi5r75VMtw2?p=preview
【问题讨论】:
-
StackOverflow 不是让您要求人们为您编写代码的地方。向我们展示您的尝试并做出扎实的努力
-
好的,我会以正确的方式上传它,代码甚至不起作用
-
与其试图关闭这个帖子,不如互相帮助。我正在努力尝试了解这个主题是否甚至可以在 Angular 2 中使用。如果不是,我不会迁移到 Angular 2 或使用它。我已经在互联网上传递了我的例子,但我的案例没有可靠的答案。
标签: javascript angular