我想访问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)
...
}
感谢您的回答。
答案 0 :(得分:0)
在组件完全加载并呈现其视图后定义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'
};
}
}