4

I have a function on a button click which I want it to add a new line to the current widgets data so that it will add a new one to the current.

Here is the code:

app.component.html

 <a (click)="addWidget()" class="btn btn-primary pull-right navbar-btn">Add Widget</a>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  public widgets: any;

  constructor() {
    let count = 1;
    this.widgets = [
      { id: 1, title: 'Widget 1', config: { row: 1, col: 1, sizex: 1 }},
      { id: 2, title: 'Widget 2', config: { row: 1, col: 2, sizex: 1 } },
  ];
    this.widgets.map(() => {
      count++;
    });
  }

  addWidget() {
    console.log('This will add a new widget');
  }  

}

How can I do this?

7
  • 2
    Try adding this.widgets.push({ id: 3, title: 'Widget 3', config: { row: 1, col: 3, sizex: 1 }}) to addWidget()? Commented Dec 18, 2017 at 10:24
  • 1
    By the way, what the point of that .map() function? To get amount of entries inside of an array just use the .length property. Commented Dec 18, 2017 at 10:27
  • There is little advantage in using typescript if you define everything as any. Try creating a class or interface for widget and config. Commented Dec 18, 2017 at 10:27
  • 1
    So something like this might work? this.widgets.forEach(widget => widget.config.row = widget.config.row+1) Commented Dec 18, 2017 at 10:34
  • 1
    Possible duplicate of How to append something to an array? Commented Dec 18, 2017 at 10:48

2 Answers 2

10

You are using an array widgets and can use the push method to add an element at the end of array. To maintain dynamic id and name we can use the length property of Array's like below:

addWidget() {
    const title: string = 'Widget ' + this.widgets.length;
    this.widgets.push({ id: this.widgets.length + 1, title: title, config: { row: 1, col: 3, sizex: 1 } })
}
Sign up to request clarification or add additional context in comments.

3 Comments

this.widgets.length+1 since he starts from Widget 1
What if... the first widget [0] gets removed and another one gets added, you end up with two widgets that have the same ID.
@Eric In that case the OP needs to keep a counter which is always incremented on push and never decremented. Then we case use that counter for id
1

You can do this:

  addWidget() {
this.widgets.push({ id: 3, title: 'Widget 3', config: { row: 1, col: this.widget.length, sizex: 1 }})
  }

1 Comment

Do NOT just copy and paste my code. To make it a valid answer you need to explain the code a bit.

Your Answer

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