【发布时间】:2017-10-19 19:33:44
【问题描述】:
我正在尝试模拟一组动态问题。想想一个测验,其中一个问题是选择题,第二个是单选题,第三个是是不是......等等。
使用 Angular 4.1,我认为使用 ngTemplateOutlet 进行模板化将是实现此目的的最佳方式,我的想法是我可以将所有复选框的样式设置为相同,并且所有单选按钮都相同等。
@Component({
selector: 'my-component',
template: `
<div *ngFor="let item of items">
<ng-template [ngTemplateOutlet]="item.type" [ngOutletContext]="{ item: item }"></ng-template>
</div>`
})
export class MyComponent {
@Input() items: any[];
}
@Component({
selector: 'my-app',
template: `
<div>
<my-component [items]="questions">
<ng-template #question let-item="item">{{item?.question}}</ng-template>
<ng-template #check let-item="item">checkboxes here {{item?.type}} - {{item?.values}}</ng-template>
<ng-template #radio let-item="item">radio buttons here{{item?.type}} - {{item?.values}}</ng-template>
<ng-template #bool let-item="item">boolean here{{item?.type}} - {{item?.values}}</ng-template>
<ng-template #textbox let-item="item">textbox here{{item?.type}} - {{item?.values}}</ng-template>
</my-component>
</div>`
})
export class App {
@ViewChild('question') question;
@ViewChild('type') type;
@ViewChild('values') values;
questions = [
{ question: "my checkbox question", type: "check", values: ["checkbox1","checkbox2","checkbox3","checkbox4"] },
{ question: "my radiobutton question", type: "radio", values: ["radio1","radio2","radio3","radio4"] } ,
{ question: "my boolean question", type: "bool", values: ["yes", "no"] } ,
{ question: "my textbox question", type: "textbox", values: ["maybe something maybe nothing"] }
];
我已经created this plunker as a proof of concept 努力,但它不起作用。所有代码都在src/app.ts 文件中。
我想要的是这样的:
My checkbox question?
checkbox 1, checkbox2, checkbox3
my radio button question
radiobutton1, radiobutton2, radiobutton3
my boolean question?
yes, no
如何修改此代码以使用变量的值来指示要使用的模板?
【问题讨论】:
-
ngTemplateOutlet应该是TemplateRef而你正在传递string -
我会加载组件而不是模板。在我看来,为您提供更多独立的功能实现和更多的动态化。我发布了我的答案,为您提供了另一种观点,以我的拙见,这可能是一种不错的方法。 (并不是说模板加载不正确,我只是为您提供一种可能有用的不同方法)
标签: angular ng-template