我有一个实现手风琴的登陆页面。手风琴中的组数由定义属性的对象列表(标题,活动......等)管理。手风琴的每个面板都包含一个特定的子组件。我想将这些组定义为:
@Component({
selector: 'aa-home',
template: require('./home.component.html'),
styles: [require('./home.component.scss')],
directives: [ACCORDION_DIRECTIVES, QUOTE_COMPONENTS]
})
export class HomeComponent implements OnInit {
public oneAtATime: boolean = true;
public groups: AccordianGroup[] = [];
constructor() {
this.groups.push(new AccordianGroup(true, 'Quote', 'quote', '<aa-quote (response)="onContinue($event)"></aa-quote>'));
this.groups.push(new AccordianGroup(false, 'Introduction', 'intro', '<aa-intro (response)="onContinue($event)"></aa-intro>'));
this.groups.push(new AccordianGroup(false, 'Applicant Information', 'applicant', '<aa-applicant (response)="onContinue($event)"></aa-applicant>'));
this.groups.push(new AccordianGroup(false, 'Details', 'details', '<aa-details(response)="onContinue($event)"></aa-details>'));
this.groups.push(new AccordianGroup(false, 'Review', 'review', '<aa-review (response)="onContinue($event)"></aa-review>'));
this.groups.push(new AccordianGroup(false, 'Payment', 'payment', '<aa-payment (response)="onContinue($event)"></aa-payment>'));
}
ngOnInit() {
console.log(_.capitalize('starting home'));
}
onContinue(message): void {
let index = _.findIndex(this.groups, function(x) { return x.name === message.componentName; });
if (index < this.groups.length - 1) {
this.groups[index].isActive = false;
this.groups[index + 1].isActive = true;
}
}
toggleActive(group): void {
this.groups.forEach(function(x) { x.isActive = false; });
group.isActive = !group.isActive;
}
}
class AccordianGroup {
constructor(
public isActive: boolean,
public title: string,
public name: string,
public template: string
) { }
}
像这样的HTML:
<div *ngFor="let group of groups">
<div class="accordion" (click)=toggleActive(group)>{{group.title}}</div>
<div class="panel" [ngClass]="{show: group.isActive}" [innerHTML]="group.template"></div>
</div>
这不起作用......什么都没有呈现。感觉好像我以错误的方式解决这个问题,但我无法解决这个问题。这背后的想法是,取决于用户...我需要过滤一些组,并且真的...在html中没有十几个或更多组具有完全相同的代码,除了子组件的一行被放置。这甚至可能吗?
答案 0 :(得分:0)
您无法使用new
创建组件。组件由Angular从视图中的HTML创建,来自ViewContainerRef.createComponent()
对于ViewContainerRef.createComponent()
示例,请参阅Angular 2 dynamic tabs with user-click chosen components(这是一个非常类似的用例)
要从标记创建组件,请在父组件类中构建数据(模型),然后使用AccordianGroup
的选择器创建元素。
public groups: AccordianGroup[] = [];
constructor() {
this.groups = [...];
...
}
<div *ngFor="let group of groups">
<div class="accordion" (click)=toggleActive(group)>{{group.title}}</div>
<div class="panel" [ngClass]="{show: group.isActive}"><accordian-group [data]="group.data"></accordian-group></div>
</div>