Rachmat Chang
Rachmat Chang

Reputation: 197

Looping in Angular 2

whether angular 2 can perform its function in the loop?

i have code :

    setValueToForms(value) : void {
    if(value.length > 0){
        if(this.validationDataInput(value)== true){
            this.rows = value[0];
            if(this.rows['id']){
                this.id = this.rows['id'];
            }
            this.form.setValue({
                'id': this.id,
                'name': this.rows['name'],
                'description': this.rows['description'],
                'category': this.rows['category']
            });
            this.selectedRolesOld = value[0]['rolesList'];
            this.selectedRoles = this.selectedRolesOld;
            console.log(this.selectedRolesOld);
            this.statusForm = 'Edit';
        }
    }
    else{
        this.statusForm = 'Add';
    }
}

i want to loop this.selectedRoles, can anyone give me a clue about that ?

Upvotes: 0

Views: 170

Answers (2)

Steve G
Steve G

Reputation: 13367

To loop through items in array you can the newer [].forEach syntax as follows:

// assuming this.selectedRoles is an array
this.selectedRoles.forEach((_role) => {  
  // Do whatever test/work you need  
  if (_role === somethingToCompare) {  
    //...  
  }  
});

Or you can use a standard for loop:

// assuming this.selectedRoles is an array
for (let i = 0; i < this.selectedRoles.length; i++) {
  // Do whatever test/work you need  
  if (this.selectedRoles[i] === somethingToCompare) {  
    //...  
  }  
}

Note: Untested code written on an iPad. :)

Upvotes: 1

Megha shah
Megha shah

Reputation: 232

You can also do with for loop. Below code is written in typescript.

for (let i = 0; i < this.array.length; i++) {
   // write your code here
}

Upvotes: 0

Related Questions