以角度 6 动态添加 div 容器 [英] dynamically add div container in angular 6

查看:25
本文介绍了以角度 6 动态添加 div 容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在angular中动态添加div容器?

请看我的html代码.每当我单击添加"按钮时,都会在该按钮的左侧添加一个新 div.动态地它应该根据点击的方式添加多个容器.一切都应该在水平方向上添加.如果默认情况下是更多容器,则应添加滚动并保持统一.任何人都可以帮我在 angular 6.

中做到这一点

#content{宽度:100%;高度:90px;边框:1px纯黑色;}#contentInside{宽度:100px;高度:70px;边距:7px;边框:1px纯黑色;显示:inline-flex;}

<div id="contentInside">

<按钮(点击)="添加()">添加</button>

我是角度的新手.请任何人帮助我做到这一点.

解决方案

最简单的方法是使用数组.让我来告诉你怎么做.

这是stackblitz

我创建了一个空元素数组,并称之为containers.

每次用户点击 Add 按钮时,我都会向这个数组推送另一个元素.我推送的元素无关紧要,所以我推送了数组的当前长度,所以它最终会像 [0, 1, 2, 3, 4...]

@Component({选择器:'my-comp',模板:`<div id="内容"><div id="contentInside" *ngFor="让容器的容器"></div><按钮(点击)="添加()">添加</button>

`,样式:[`#内容{宽度:100%;高度:90px;边框:1px纯黑色;}#contentInside{宽度:100px;高度:70px;边距:7px;边框:1px纯黑色;显示:inline-flex;}`]})导出类 MyComponent 实现 OnInit {容器 = [];构造函数(){}ngOnInit() { }添加() {this.containers.push(this.containers.length);}}

How to dynamically add div containers in angular?.

Please look at my html code. Whenever I will click "Add" button, one new div should add left side of that button. Dynamically it should add multiple containers based on how any clicks. Everything should add in horizontal wise. If it is more containers by default it should add scroll and it be in uniform. Can anyone please help me to do this in 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>

I am new in angular. Please anyone help me to do this.

解决方案

Easiest way to do this is with an array. Let me show you how.

Here is the stackblitz

I create an array of empty elements, and call it containers.

Every time, user clicks on Add button, I push another element to this array. The element I push does not matter, so I push the current length of the array so it will end up like [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);
  }
}

这篇关于以角度 6 动态添加 div 容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆