Angular basvandenberg/ng简单字符串数组选择问题

Angular basvandenberg/ng简单字符串数组选择问题,angular,angular5,angular-ngselect,Angular,Angular5,Angular Ngselect,我正在使用以下ng select模块,在使用简单阵列时遇到问题 它期望的选项格式是对象数组: { value: string; label: string; } 但在提供数据的情况下,我没有这个选择 我的目标: { name: "something", tags: ["option1","option2","option3"], tagPrimary: "", ... } 在my Angular5组件模板中: <ng-select

我正在使用以下ng select模块,在使用简单阵列时遇到问题

它期望的选项格式是对象数组:

{
   value: string;
   label: string;
}
但在提供数据的情况下,我没有这个选择

我的目标:

{
    name: "something",
    tags: ["option1","option2","option3"],
    tagPrimary: "",
    ...
}
在my Angular5组件模板中:

<ng-select
      placeholder="Select a primary option..."
      [(ngModel)]="obj.tagPrimary"
      [options]="obj.tags">
</ng-select>
现在,当使用此选项时,生成的下拉列表有3个选项,但不显示任何内容,因为它正在查找具有标签键的对象

我试图创建一个能正确格式化数据的函数

function format(tags){
    arr=[];
    _.each(tags,function(tag){
        obj.push({label: tag, value: tag});
    }
    return obj;
}

<ng-select
          placeholder="Select a primary option..."
          [(ngModel)]="obj.tagPrimary"
          [options]="format(obj.tags)">
</ng-select>
虽然它现在确实正确地呈现下拉列表,但这些项目是不可选择的。在DOM检查器中查看源代码时,每个选项上的style属性似乎都会消失/重新出现,就像在反复触发函数时重新初始化一样

函数是否正确创建?

您应该将format方法的返回值分配给组件中的另一个“属性”,并在模板中使用该属性,而不是直接在模板中分配[options]=formatobj.tags,这可能会导致方法在每个更改检测周期中触发

假设您的obj在ngOnInit中可用,否则当您的obj属性在组件中的值可用时,您应该进行此赋值

optionsForSelect: { label: string; value: string; }[]; // specifying the type, not necessary though, a type of 'any[]' would be sufficient

format(tags){
  arr=[];
  _.each(tags,function(tag){
      arr.push({label: tag, value: tag});
  }
  return arr;
}

ngOnInit() {
  //after you get 'obj' property
  this.optionsForSelect = this.format(this.obj.tags);
}
在您的组件中

optionsForSelect: { label: string; value: string; }[]; // specifying the type, not necessary though, a type of 'any[]' would be sufficient

format(tags){
  arr=[];
  _.each(tags,function(tag){
      arr.push({label: tag, value: tag});
  }
  return arr;
}

ngOnInit() {
  //after you get 'obj' property
  this.optionsForSelect = this.format(this.obj.tags);
}
在模板中

<ng-select
    placeholder="Select a primary option..."
    [(ngModel)]="obj.tagPrimary"
    [options]="optionsForSelect">
</ng-select>

谢谢,这是我需要的方向。