简体   繁体   English

Angular 4 ng选择动态默认值

[英]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. 我在Angular 4项目中有一个ng-select组件的表单,其中显示了用户的角​​色。 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. 为了做到这一点,我在ngOnInit中使用FormControls。 Because I get the default values from a service, they are loading so slow according to the initialisation of the FormGroup. 因为我从服务获取默认值,所以根据FormGroup的初始化,它们的加载速度如此之慢。 I am calling both of them in ngOnInit but everytime the FormGroup runs before. 我在ngOnInit中都调用它们,但是每次FormGroup运行之前。 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. 这是因为默认情况下,http调用是异步的,并且在完成对表单组的调用时必须设置值。

  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 从@ angular / forms导入FormBuilder和FormGroup

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.. 尝试使用@Input这样传递数组。

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

Now instead of using ngOnInit , try defining it in the constructor instead 现在,不要使用ngOnInit ,而是尝试在构造函数中定义它

/**
 * 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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