Add array in Angular

0

I need to know how to add array in the Angular component (TypeScript)

addCostCenter(i){
    this.costCenter.push(i);
  }

Every time I click, there will be a function that will add an array; I will have many one-dimensional arrays.

I need to know the way in which I can add all the arrays that are inside and that if the sum gives more than 100, an error appears; or if it gives less than 100, an error. The sum of all the arrays that you add must be 100.

In conclusion; I want to know how you can add the array and how to make it so that it says that the sum must be 100. If it is more or less than 100; I get an error.

    
asked by Jhonatan Cardona Valencia 08.05.2018 в 21:34
source

1 answer

1

Add a Boolean variable to indicate when the error message should be displayed using ngIf .

Example

Component

@Component({
  selector: 'app-costcenter',
  templateUrl: './nombre.component.html',
})
export class TuComponent {
  private showError: boolean = false;
  private constCenter: Array<any> = [];

  public addCostCenter(i): void {
    this.costCenter.push(i);
    if (this.sumCosts() > 100) {
      this.showError = true;
    }
  }

  public sumCosts(): number {
    return this.costCenter.reduce((acc, val) => (
      acc + val.reduce((accx, valx) => accx + valx, 0)
    ), 0);
  }
}

Template

<section>
  <button (click)="addCostCenter(10)">Add cost center</button>
  <div className="error" *ngIf="showError">You has been passed of 100 units</div>
</section>
    
answered by 09.05.2018 в 17:17