mercredi 25 octobre 2017

Remove duplicate and checked elements of array

I have users and each of them can have some company role. I created popup modal that get all company roles in list with checkboxes. For every role that that user have at that moment, role is checked in list. When uncheck role and submit, I want that list to update with .put method.

Problem is that I made function, but that function is making double roles whenever I leave any of previous roles still checked. Seems that they get in array in way that function see them as checked or something like that.

My ts:

export class AddRolePopupComponent extends PopupAbstract<any> implements OnInit {

userRoles = [];
userRolesNames = [];
selectedRoles = [];


constructor( private userService: UserService, private companyService: CompanyService, public dialog: DialogRef<any> ) {

    super( dialog, dialog.context );
}

ngOnInit() {        
    this.userService.getRolesForUser(this.context.id).subscribe(
        response => { this.handleSucess( response ); },
        error => { console.error( error ); },
    );
    }


handleSucess(response) {
        this.userRoles = response;
        this.userRolesNames = response.map(userRole => userRole.name);
}

selectRole(category, event , role) {
    var index = this.userRoles.indexOf(role);
    if (event.target.checked) {
        this.userRoles.push(role);
     } else {
        if (index !== -1) {
            this.userRoles.splice(index, 1);
        }
    }

}

submitRole(){
    console.log(this.userRoles);
}

userRoles = response on handleSucess is getting me all roles that selected user currently have.

html:

<div class="roles-div">
<div style="text-align: center;">
    <label class="label-roles">Select User Roles</label>
</div>
<form #rolesForm="ngForm" (ngSubmit)="submitRole(rolesForm)" >
<div class="flex-column-center">
    <div class="flex-center width90 height300 checkbox-div">
        <div>
            <ul>
                <li *ngFor="let role of context.roles">
                    <input class="roles-li" type="checkbox" [checked]="userRolesNames.indexOf(role.name)>-1"  name="role"  (change)="selectRole(option, $event, role)">
                </li>
            </ul>
        </div>
    </div>
    <div class="flex-column-center2 width35">
        <button class="btn-main10" type="submit">Submit</button>
    </div>
</div> 
</form>




Aucun commentaire:

Enregistrer un commentaire