如何在angular中动态添加div容器?
请看我的html代码。每当我单击“添加”按钮时,一个新的 div 应该添加到该按钮的左侧。动态地,它应该根据点击的方式添加多个容器。一切都应该水平添加。如果默认情况下它是更多的容器,它应该添加滚动并且它是统一的。谁能帮我在 angular 6.
#content{
width:100%;
height:90px;
border:1px solid black;
}
#contentInside{
width:100px;
height:70px;
margin:7px;
border:1px solid black;
display:inline-flex;
}
<div id="content">
<div id="contentInside">
</div>
<button (click)="add()">Add</button>
</div>
我是 Angular 的新手。请任何人帮助我做到这一点。
最佳答案
最简单的方法是使用数组。让我告诉你怎么做。
这是 stackblitz
我创建了一个空元素数组,并将其命名为容器
。
每次用户点击Add
按钮时,我都会将另一个元素推送到该数组。
我压入的元素并不重要,所以我压入数组的当前长度,所以它最终会像 [0, 1, 2, 3, 4...]
@Component({
selector: 'my-comp',
template: `
<div id="content">
<div id="contentInside" *ngFor="let container of containers"></div>
<button (click)="add()">Add</button>
</div>
`,
styles: [`
#content{
width:100%;
height:90px;
border:1px solid black;
}
#contentInside{
width:100px;
height:70px;
margin:7px;
border:1px solid black;
display:inline-flex;
}
`]
})
export class MyComponent implements OnInit {
containers = [];
constructor() { }
ngOnInit() { }
add() {
this.containers.push(this.containers.length);
}
}
关于html - 以 Angular 6动态添加div容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50924713/