简体   繁体   English

如何分配

[英]How to assign <ng-select [multiple]=isMultiple varibale dynamically?

I need to change a select box behavior dynamically.我需要动态更改选择框的行为。 The below approach is not working, because this variable we cannot set dynamically after calling a service.以下方法不起作用,因为我们无法在调用服务后动态设置此变量。 The component will initialize before the service getting triggered.该组件将在服务被触发之前初始化。 Any workaround we have for such situations?对于这种情况,我们有什么解决方法吗?

    <ng-select
             [multiple]=isMultiple
    
    
    ngOnInit(){
        this.testService.isMultiple().subscribe(
            (isMultiple: boolean): void => {
        this.isMultiple = true;
        }
    }

Trigger manual change detection using ChangeDetectorRef .使用ChangeDetectorRef触发手动更改检测。

The value to the isMultiple is assigned from asynchronous operation, which takes some time for the completion of async operation and retrieval of results. isMultiple的值是从asynchronous操作中分配的,这需要一些时间来完成异步操作和检索结果。 So, the angular fails to auto-detect the change of isMultiple .因此,角度无法自动检测isMultiple的变化。 In such cases, we have to manually trigger the change detection once the asynchronous operation has been completed.在这种情况下,我们必须在异步操作完成后手动触发change detection

import {ChangeDetectorRef} from "@angular/core";

@Component({...})
export class [className] {
  constructor( private _cdref: ChangeDetectorRef ) {}
    
  ngOnInit(){
    this.testService.isMultiple().subscribe(
      (isMultiple: boolean): void => {
        this.isMultiple = true;
        this._cdref.detectChanges();
    }
  }
}

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

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