2017-02-08 17 views
3

Suppost我有一個字符串數組:如何在Angular2中反覆打印另一個元素中的元素?

s : Array<string>=['Layer 1','Layer 2','Layer 3','Layer 4','Layer 5']; 

很容易迭代和線性打印出來:

<div *ngFor="let st of s">{{st}}</div> 

但如果我想附上DIV到另一個這樣的div:

div{ 
 
    border-color:black; 
 
    border-style:solid; 
 
    border-width:3px; 
 
}
<div>Layer 1 
 
    <div>Layer 2 
 
    <div>Layer 3 
 
     <div>Layer 4 
 
     <div>Layer 5</div> 
 
     </div> 
 
    </div> 
 
    </div> 
 
</div>

是否有棱角功能可以像這樣在div中打印div?

回答

0

據我所知,你不能在Angular本身做到這一點。最簡單的方法是創建自己的nested-div組件

嵌套div.component.ts

import { Component, Input } from '@angular/core'; 

@Component({ 
    selector: 'nested-div', 
    templateUrl: './nested-div.component.html', 
    styles: [`nested-div { display: block; }`] 
}) 
export class NestedDivComponent { 

    @Input() layers: string[]; 

    constructor() { } 

    get hasMoreLayers(): boolean{ 
     return this.layers.length > 1; 
    } 
} 

嵌套div.component.html

{{ layers[0] }}<nested-div *ngIf="hasMoreLayers" [layers]="layers | slice:1"></nested-div> 

這將生成嵌套的div結構,你在之後

0

我能夠將o ne div在另一個div中,通過獲取* ngFor的索引並給每個圖層添加大量的margin-left。這是我想出了:

<div *ngFor="let st of s;let i = index"> 
     <span [ngStyle]="{'margin-left': i + 'rem' }">{{st}}</span> 
    </div> 

這裏有一個plunker:https://plnkr.co/edit/JZ6hVM3KVfjbnJe0zGTe?p=preview

相關問題