简体   繁体   中英

Angular 4 ng-select Dynamic Default Values

I have a form for ng-select component, which shows the roles of a user, in my Angular 4 project. In that component, first I need to get the user roles and show them as default values. To be able to do that, I am using FormControls in ngOnInit. Because I get the default values from a service, they are loading so slow according to the initialisation of the FormGroup. I am calling both of them in ngOnInit but everytime the FormGroup runs before. So I can't see any of the default values on the screen. I tried to make it async but I couldn't do it.

ngOnInit() {
  this.sub = this.route.params.subscribe(params => {
      this.userTC = params['id'];
      this.getUserInfo(this.userTC); // This function works second
  });


  // This part works first
  this.form = new FormGroup({
    roles: new FormControl(this.defaultRoles)
  });
}


getUserInfo(tc) {
  this.userService.getUser(tc).subscribe(data => {
    if(data) {
      let arr = new Array<string>();

      for(i = 0; i < data.roles.length; i++) {
        switch(data.roles[i]) {
          case "admin" :
            arr[i] = '1';
          break;
          case "doktor" : 
            arr[i] = '2';
          break;
          case "hasta" :
            arr[i] = '3';
          break;
          case "lab" :
            arr[i] = "4";
          break;
        }
      }
      this.defaultRoles = arr;
    } 
  }  
}

That's because you http calls are by default async and you have to set value when the call is finished to your form group.

  form: FormGroup; constructor(private fb: FormBulider){} ngOnInit() { this.sub = this.route.params.subscribe(params => { this.userTC = params['id']; this.getUserInfo(this.userTC); // This function works second }); // This part works first this.form = this.fb.group({ roles: '' }); } getUserInfo(tc) { this.userService.getUser(tc).subscribe(data => { if(data) { let arr = new Array<string>(); for(i = 0; i < data.roles.length; i++) { switch(data.roles[i]) { case "admin" : arr[i] = '1'; break; case "doktor" : arr[i] = '2'; break; case "hasta" : arr[i] = '3'; break; case "lab" : arr[i] = "4"; break; } } this.form.get('roles').setValue(arr || []); } 

FormBuilder and FormGroup are imported from @angular/forms

In this instance your are using form control to capture the end users response to the selection. Not the storage of the list as a whole. Try using @Input to pass in the array like so..

<get-user-info
    [roles]="someArray">
<get-user-info>

Now instead of using ngOnInit , try defining it in the constructor instead

/**
 * Implementation for GetUserInfoComponent:
 */
export class GetUserInfoComponent {
    /**
     * GetUserInfoComponent constructor
     * @param builder
     */
    constructor(
        private builder             : FormBuilder
    ) {
        // init form input fields
        this.roleSelected         = new FormControl('', undefined);

        // build User Information FormControl group
        this.userInfo = this.builder.group({
            roleSelected         : this.rolesSelector
        });

        // subscribe to any form changes
        this.roleSelected.valueChanges.filter(value => value != null).subscribe((value : string) => {
            // emit updated email value event
            this.updateRole(value.trim());
        });
}

/**
 * available selectable roles
 */
@Input() roles : Array[String];

/**
 * user's selected role state
 */
roleSelected : string;

/**
 * event handler for role selection event
 */
updateRole() {
    // do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM