11

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.

2
  • So, you want multiple contentInside divs when user clicks on Add button? Commented Jun 19, 2018 at 9:45
  • yes. If i click one time it should add one container, like this how many times i will click, that much containers should add in horizontal wise Commented Jun 19, 2018 at 9:50

2 Answers 2

23

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);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Try Using this example with updated css for autoscroll:

https://stackblitz.com/edit/angular-pujraw?file=src%2Fapp%2Fapp.component.css

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.