valor-software / ng2-select

Angular based replacement for select boxes
http://valor-software.github.io/ng2-select/
MIT License
675 stars 587 forks source link

Two way binding issue with ng2-select #889

Closed stephenad closed 6 years ago

stephenad commented 7 years ago

Hi All,

Hope someone can advise where I am going wrong. I have a select list on my page where the users select the client they want to edit. On selecting a person this then populates the relevant fields for editing.

However for my ng2-select list that contains the users category I cannot get it to populate when I select a user from my user drop down. Below is my code, any advise appreciated.

Manage User HTML component

`

Please select a user to edit or enter the details for a new user you wish to add to the system

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">

 

<bs-modal [animation]="animation" [keyboard]="keyboard" [backdrop]="backdrop" (onClose)="closed()" (onDismiss)="dismissed()" (onOpen)="opened()" [cssClass]="cssClass" #deleteuserModal > <bs-modal-header [showDismiss]="true">

</bs-modal-header>
<bs-modal-body>
  <p>{{mymodaltext}}</p>
</bs-modal-body>
<bs-modal-footer>
    <button type="button" class="btn btn-default" data-dismiss="modal" (click)="modal.dismiss()">Cancel</button>
    <button type="button" class="btn btn-primary" (click)="confirmDelete()">Delete</button>
</bs-modal-footer>

<bs-modal [animation]="animation" [keyboard]="keyboard" [backdrop]="backdrop" (onClose)="closed()" (onDismiss)="dismissed()" (onOpen)="opened()" [cssClass]="cssClass" #errorModal > <bs-modal-header [showDismiss]="true">

</bs-modal-header>
<bs-modal-body>
    <p>{{mymodaltext}}</p>
  </bs-modal-body>
<bs-modal-footer>
    <button type="button" class="btn btn-default" data-dismiss="modal" (click)="modal.dismiss()">Close</button>
</bs-modal-footer>

`

Manage User component .ts code

` / !!! System Imports !!! / import { Component, OnInit, OnDestroy, ViewChild} from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { ToasterService } from 'angular2-toaster'; import 'rxjs/Rx'; import { BsModalComponent, BsModalService } from 'ng2-bs3-modal/ng2-bs3-modal';

/* Project Imports */ import { ManageUserService, AppMessagingService} from '../../../services/index'; //, DialogService import { ManageUser, NewUserInfo } from '../../../models/index';

@Component({ selector: 'manageuser', templateUrl: './manageuser.component.html', })

export class ManageUserComponent implements OnInit, OnDestroy { @ViewChild('select') selectElRef; @ViewChild('deleteuserModal') deleteuserModal: BsModalComponent; @ViewChild('errorModal') errorModal: BsModalComponent; mymodaltext: string; myForm: FormGroup; loading: boolean; liveuserlist: ManageUser[]; selectedUser = this.liveuserlist; fulluserlist: ManageUser[]; checkexistanceuserlist: ManageUser[]; title: string; message: string; confirmResult:boolean = null; beingdeleted: boolean = false; beingreset: boolean = false; userexists: number; u_id: number = 0; u_email: string; u_firstname: string; u_lastname: string; u_company: string; u_category: string; u_businesstype: string; u_mailinglist: string; u_status: string; u_admin:string; u_username: string; u_active: string; u_userrole: string; userrolestring: string; u_deleted: string; category: string; categories = []; cover: string; covers = []; public categoryitems = []; public mycategoryitems = []; public coveritems = []; public mycoveritems = [];

/ Select box properties / properties: [ 'allowClear', 'placeholder', 'items', 'multiple', 'showSearchInputInDropdown' ]

private value:any = [''];

public selectedCover(value:any):void { console.log('Selected value is: ', value); }

public removedCover(value:any):void { console.log('Removed value is: ', value); }

public refreshValueCover(value:any):void { this.value = value; }

public selectedCategory(value:any):void { console.log('Selected value is: ', value); }

public refreshValueCategory(value:any):void
{
  //  alert('"I am in refreshValueCategory and have value: '+ JSON.stringify(value) );
  this.value = value;
}

public itemsToString(value:Array = []):string { return value .map((item:any) => { return item.text; }).join(','); }

constructor ( private aMS: AppMessagingService, private manageuserService: ManageUserService, private toasterService: ToasterService, private modalservice: BsModalService, ) {}

ngOnInit(): void { this.getliveuserlist(); this.getfulluserlist(); this.getCategoryList(); this.getCoverList();

this.myForm = new FormGroup
(
  {
  email: new FormControl(),
  firstname: new FormControl(),
  lastname: new FormControl(),
  company: new FormControl(),
  businesstype: new FormControl(),
  mailinglist: new FormControl(),
  activestatus: new FormControl(),
  adminuser: new FormControl(),

}); this.myForm.controls['mailinglist'].setValue(true); this.myForm.controls['activestatus'].setValue(true); }

ngOnDestroy() {}

private UserID: number = 0; private Email: string; private Firstname: string; private Lastname: string; private Company: string; private Businesstype: string;

/ get all covers (ie non deleted)/ getCategoryList() { console.log('In Manage User - get Category list code'); this.manageuserService.getCategories() .subscribe( data => {

  this.categories = data; //Bind to view
  console.group('I have these mycategoryitems');
  console.dir(this.categories);
  console.log(this.categories.length);
  console.groupEnd();
  this.mycategoryitems.push('Select a category');
  for(let i = 0; i <=this.categories.length-1; i++)
  {
    //alert('Coverid: '+ covers[i].cover_id + ' ' + ' cover name: ' + covers[i].covername);
    this.mycategoryitems.push(this.categories[i].categoryname);
  }
  // this.mycategoryitems.push('Select a category');
  console.group('I have these mycategoryitems');
  console.dir(this.mycategoryitems);
  console.groupEnd();
  this.categoryitems = this.mycategoryitems;
},
error =>
{
   // Log errors if any
   this.aMS.messageLog('Errors', 'Error', 'Error - retrieving categories', 'Error loading category list.');
   console.log(error);
},);

}

public onChange(selecteduserid) { if(selecteduserid === 0) { this.myForm.reset(); this.UserID = 0; } else { console.group('user list'); console.dir(this.liveuserlist); console.groupEnd(); this.u_id = this.liveuserlist.find((item: any) => item.id === selecteduserid).id; this.u_email = this.liveuserlist.find((item: any) => item.id === selecteduserid).email; this.u_firstname = this.liveuserlist.find((item: any) => item.id === selecteduserid).first_name; this.u_lastname = this.liveuserlist.find((item: any) => item.id === selecteduserid).last_name; this.u_company = this.liveuserlist.find((item: any) => item.id === selecteduserid).company; this.u_businesstype = this.liveuserlist.find((item: any) => item.id === selecteduserid).businesstype; this.u_category = this.liveuserlist.find((item: any) => item.id === selecteduserid).businesstype;

  console.log('current u_businesstype: ' + this.u_businesstype);
  if(this.u_category.toLowerCase().includes('underwriter'))
  {
    alert('I have this category at the moment: ' + this.u_category);
    console.dir('I have this category at the moment: ' + this.u_category);
    this.value = (this.categories.find((item: any) => item.categoryname  === ('Underwriter')));
    console.dir(this.value);

  }
  else
  {
    alert('I do not have such a category');
  }

  this.UserID = this.liveuserlist.find((item: any) => item.id === selecteduserid).id;
  this.Email = this.liveuserlist.find((item: any) => item.id === selecteduserid).email;
  this.Firstname = this.liveuserlist.find((item: any) => item.id === selecteduserid).first_name;
  this.Lastname = this.liveuserlist.find((item: any) => item.id === selecteduserid).last_name;
  this.Company = this.liveuserlist.find((item: any) => item.id === selecteduserid).company;
  this.Businesstype = this.liveuserlist.find((item: any) => item.id === selecteduserid).businesstype;

/**** this is my code where I am trying to set the category select field to be Underwriter or other options based on what they user has but I cannot get the select box to show the "value" ie underwirter /

  this.userrolestring = this.liveuserlist.find((item: any) => item.id === selecteduserid).user_role;
  if(this.userrolestring.includes('Administrator'))
  {
    this.myForm.controls['adminuser'].setValue(true);
  }
  else
  {
    this.myForm.controls['adminuser'].setValue(false);
  }

  let Activestatusvalue = this.liveuserlist.find((item: any) => item.id === selecteduserid).active;
  if(Activestatusvalue === '1')
  {
    this.myForm.controls['activestatus'].setValue(true);
  }
  else
  {
    this.myForm.controls['activestatus'].setValue(false);
  }

  let Mailinglistvalue = this.liveuserlist.find((item: any) => item.id === selecteduserid).mailinglist;
  if(Mailinglistvalue === '1')
  {
    this.myForm.controls['mailinglist'].setValue(true);
  }
  else
  {
    this.myForm.controls['mailinglist'].setValue(false);
  }
}

} } `

Any advice on what I am doing wrong would be greatly appreciated

Regards Andy

sonukapoor commented 7 years ago

Can you provide a plnkr?

stephenad commented 7 years ago

@sonukapoor,

I have tried to make a plnkr [https://plnkr.co/edit/IV20AmQToD9z1sbqZsJy?p=preview] but it is not loading I had to modify it so it had static arrays as my primary system get data from a database.

I am using angular 2 as the system currently cannot be upgraded to angular 4 and plunker seems to force me to use angular 4

I have simplified the code so now I just have the users dropdown list the user fields and then the dropdown list called category that I am trying to populate when I select the user.

Please let me know know your thoughts.

Thanks Andy

stephenad commented 6 years ago

Did this a different way in the end see plunker:

[https://plnkr.co/edit/z2RCRX3KEw02FLhVxXKe?p=preview](Plunker Demo)

sonukapoor commented 6 years ago

So sorry for the delay. Did you get it working?

stephenad commented 6 years ago

Hi Sonukapoor,

Yes I did thank you for the reply.

Side question do you have any experience using https://stuk.github.io/jszip/ in angular 2?

Thanks Andy

sonukapoor commented 6 years ago

No unfortunately not.

stephenad commented 6 years ago

No problem, Thanks and have a great day.