首页 > 解决方案 > TypeError:无法读取未定义的属性“加入”

问题描述

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

管理员.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>

标签: htmlangulartypescript

解决方案


您必须初始化您的模型,因为undefined当您尝试在ngOnInit.

public value: string[] = [];

推荐阅读