我想根据项目模板和来自Angular4中json的项目列表创建样式元素列表。我的代码目前如下:
@Directive({selector: '[mnItem]'})
export class MnItemDef {
constructor(private _viewContainer: ViewContainerRef, private templateRef: TemplateRef<any>) { }
@Input() mnItem : any;
ngOnInit() {
console.log(this.mnItem);
this._viewContainer.createEmbeddedView(this.templateRef, {$implicit:this.mnItem});
}
}
@Component({
selector: 'mn-element',
template:'<div [fxFlex]="itemWidth" *mnItem="let item"><ng-container></ng-container></div>'
})
export class MnElementDef {
@Input() itemWidth;
@Input() item;
constructor() {}
ngOnInit(){
console.log(this.item);
}
}
@Component({
selector: 'mn-flex-cards',
templateUrl: './mn-flex-cards.component.html',
styleUrls: ['./mn-flex-cards.component.css']
})
export class MnFlexCardsComponent implements OnInit {
@ViewChild('placeHolder', {read: ViewContainerRef}) private _placeHolder: ViewContainerRef;
@Input() items = [];
constructor(private _cmpFctryRslvr: ComponentFactoryResolver) {
}
doGetPage(){
if (this.mode == "memory"){
this.items = this.filtered.slice(this.pageSize*this.pageIndex,this.pageSize*(this.pageIndex+1) )
}
for (let itm of this.items){
let cmp = this.createComponent(this._placeHolder, MnElementDef);
cmp.instance.itemWidth = this.itemWidth;
cmp.instance.item = itm;
this._placeHolder.insert(cmp.hostView);
}
}
ngOnInit() {
if(this.mode == "memory"){
this.itemSize = this.memoryItems.length;
this.filtered = this.memoryItems.slice(0,this.memoryItems.length);
}
this.doGetPage();
}
}
模板
<div fxLayout='row' class="zero" fxLayoutAlign="space-around center" fxLayoutWrap fxLayoutAlign="center stretch">
<ng-template #placeHolder></ng-template>
</div>
和使用元素:
<mn-flex-cards
[memoryItems]="items"
mode="memory"
[filter]="false"
[pager_bottom]="false"
backend="bms">
<mn-element>
<div style="margin:10px;" *mnItem="let item">
<md-card class="filo-card" >
<md-card-header>
<md-card-title><span class="title">{{item.title}}</span></md-card-title>
<md-card-subtitle><span class="subtitle">{{item.subtitle}}</span></md-card-subtitle>
</md-card-header>
<md-card-content>
<div style="width:10%; float:left;">
<img src="{{item.img}}">
</div>
<div style="width:90%; float:right; text-align:right;">
<p class="descr" [innerHtml]="item.descr"></p>
</div>
<div style="clear:both;"></div>
</md-card-content>
</md-card>
</div>
</mn-element>
</mn-flex-cards>
由于某种原因,结果总是
PagesPointsComponent.html:24错误类型错误:无法读取null的属性“title” at Object.eval [as updateRenderer](PagesPointsComponent.html:24) at Object.debugUpdateRenderer [as updateRenderer](vendor.bundle.js:sourcemap:70245) 在checkAndUpdateView(vendor.bundle.js:sourcemap:69392) 在callViewAction(vendor.bundle.js:sourcemap:69752) at execEmbeddedViewsAction(vendor.bundle.js:sourcemap:69710) 在checkAndUpdateView(vendor.bundle.js:sourcemap:69388) 在callViewAction(vendor.bundle.js:sourcemap:69752) 在execComponentViewsAction(vendor.bundle.js:sourcemap:69684) 在checkAndUpdateView(vendor.bundle.js:sourcemap:69393) 在callViewAction(vendor.bundle.js:sourcemap:69752)