【问题标题】:TypeError: Cannot read property 'join' of undefinedTypeError:无法读取未定义的属性“加入”
【发布时间】:2018-10-22 11:31:51
【问题描述】:

我正在尝试将 select2 集成到我的 html 模板中,但我不断收到此错误。我希望能够一次选择多个选项 我不知道该怎么做。 帮助将不胜感激。

admin.ts

import { Component, OnInit } from '@angular/core';
import { Select2OptionData } from 'ng2-select2';

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.scss']
})
export class AdminComponent implements OnInit {

  public candidateData: Array<Select2OptionData>;
  public options: Select2Options;
  public value: string[];
  public current: string;

  constructor() { }

  ngOnInit() { this.candidateData = [
    { id: '1', text: 'Mohammadu Buhari' },
    { id: '2', text: 'Atiku Abubakr' },
    { id: '3', text: 'John Doe'},
    { id: '4', text: 'Someone Else'}];

    this.options = {
      multiple: true
    };

    this.current = this.value.join(' | ');
  }

  changed(data: {value: string[]}) {
    this.current = data.value.join(' | ');
  }


}
<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
      <label>Candidates</label>
      <select2 
      [data] = "exampleData"
      [options] = "options"
      [width] = "500"
      [value] = "value"
      (valueChanged) = "changed($event)"
      ></select2>
    </div>
  </div>
</div>

【问题讨论】:

  • 初始化值public value: string[] = []
  • 我明白了。但是在我初始化模型后,错误消失了,但我仍然无法选择多个
  • 我建议提供您正在使用的库的链接,将代码更新为现在的样子,更新问题标题并在帖子末尾添加一个带问号的问题:)。

标签: html angular typescript


【解决方案1】:

您必须初始化您的模型,因为当您尝试在ngOnInit 中访问它时它是undefined

public value: string[] = [];

【讨论】:

  • 我明白了。但是在我初始化模型后,错误消失了,但我仍然无法选择多个
  • [data] = "exampleData" 更改为[data] = "candidateData"
猜你喜欢
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多