【问题标题】:How to pass a variable into select2 element如何将变量传递给select2元素
【发布时间】:2018-04-17 09:09:29
【问题描述】:

我想访问tagCreation 函数中的一个变量(这里称为“正则表达式”),但是当我想打印它时,她是未定义的。

我有以下代码:

var regex = ...;

select2Obj = {
  data: this.selectedValues,
  tags: true,
  tokenSeparators: [',', ' '],
  selectOnClose: true,
  placeholder: this.placeholder,
  width: '100%',
  createTag: this.tagCreation,
  templateSelection: this.template,
  theme: 'darkred'
};

tagCreation(params) {
  if (params.term.match(this.regex) === null) {
    // Return null to disable tag creation
    return null;
  }
  return {
    id: params.term,
    text: params.term
  };
}

initSelect2(): void {
  this.select2 = $(this.el.nativeElement)
    .find('select')
    .select2(this.select2Obj)
    ...
}

感谢您的回答。

【问题讨论】:

    标签: angular jquery-select2


    【解决方案1】:

    在组件完全加载并呈现其视图后定义您的 select2Obj。

    例如:

    declare const regex: RegExp = /^(330|331|333|334|335|336|337|338|339|360|366|368|340|342|344|345|346|347|348|349|351|320|324|327|328|329|380|388|389|391|392|393|370|350|377|373)[0-9]{6,7}$/i;
    
    export class YourClassName implements AfterInit {
    
      constructor() {}
    
      tagCreation(reg, params?) {
        if (params.term.match(reg) === null) {
          // Return null to disable tag creation
          return null;
        }
        return {
          id: params.term,
          text: params.term
        };
      }
    
      initSelect2(): void {
        this.select2 = $(this.el.nativeElement)
          .find('select')
          .select2(this.select2Obj)
          ...
      }
    
      ngAfterViewInit() {
        select2Obj = {
          data: this.selectedValues,
          tags: true,
          tokenSeparators: [',', ' '],
          selectOnClose: true,
          placeholder: this.placeholder,
          width: '100%',
          createTag: this.tagCreation(regex),
          templateSelection: this.template,
          theme: 'darkred'
        };
      }
    
    
    }

    【讨论】:

    • 当我这样做时,regextagCreation() 中是undefined
    • 你确定在你的正则表达式分配之前没有初始化 tagCreation() 吗?
    • 如何查看?
    • 当我将它添加到 ngAfterViewInit() 时,tagCreation() 被调用,但 regex 再次未定义。在ngOnInit() 中,tagCreation() 永远不会被调用。
    • 再次编辑。这对我有用。如果仍然无法正常工作,则您的代码部分可能存在一些您尚未发布的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    相关资源
    最近更新 更多