我想根据一些计算分配CSS类。这是我的组件类:
@Component({
selector: 'app-render-json',
template: `<div [innerHtml]="html | safeHtml"></div>`,
styleUrls: ['./render-json.component.css'] , encapsulation: ViewEncapsulation.ShadowDom
})
export class RenderJsonComponent {
@Input() myJson: any;
html = ``;
static levelDeep = 1
ngOnInit() {
this.renderJson(this.myJson)
}
renderJson(obj) {
RenderJsonComponent.levelDeep = RenderJsonComponent.levelDeep + 1
for(var key in obj) {
if(key != 'id') {
this.html = this.html + `<div class="col-md-${RenderJsonComponent.levelDeep} col-md-offset-${RenderJsonComponent.levelDeep}">${obj[key]}</div>`
// This does not work but I want to do something like this
}
}
}
}
基本上,我需要使用偏移量类通过引导程序以GRID样式呈现一些JSON,但这无法正常工作。任何帮助表示赞赏。
最佳答案
@Component({
selector: 'app-render-json',
template: `<div [innerHtml]="safeHtml"></div><div *ngFor="jsonElements as element" class="element.class">element.obj</div>`,
styleUrls: ['./render-json.component.css'] , encapsulation: ViewEncapsulation.ShadowDom
})
export class RenderJsonComponent {
@Input() myJson: any;
myLevelDeep = 1;
jsonElements = [];
ngOnInit() {
this.renderJson(this.myJson)
}
renderJson(obj) {
this.myLevelDeep = RenderJsonComponent.levelDeep + 1
for(var key in obj) {
if(key != 'id') {
jsonElements.push({class:"col-md-" + this.myLevelDeep + " col-md-offset-" + this.myLevelDeep, obj: obj[key]});
}
}
}
}