【问题标题】:Cannot read properties of undefined (reading 'substr')无法读取未定义的属性(读取“substr”)
【发布时间】:2021-09-22 20:18:07
【问题描述】:

您好,我正在尝试根据一些计算从字符串中获取子字符串,但在浏览器控制台中出现此错误:

        
        TypeError: Cannot read properties of undefined (reading 'substring')
           at MessageVariantCardInputComponent.onInput 
           at MessageVariantCardInputComponent_input_HostBindingHandler
        

当使用下面的代码示例获取“value”的子字符串值时

代码:

        
      
    @HostListener('input') onInput() {  
    this.triggerFound = false;
    this.triggerName = '';
    const native = this.element.nativeElement;
    console.log("=== native dropdown", native)
    const value = native.value;
    const currentPos = native.selectionStart - 1;
    
    for (const key of Object.keys(this.triggers)) {
        const trigger = this.triggers[key];
        const triggerLen = trigger.length;
        const extractedString = value.substr(currentPos - triggerLen + 1, triggerLen);
        const found = extractedString === trigger;
        const isFirstTrigger = key === 'firstElement';
    
        if ((isFirstTrigger && found && currentPos === 0) || // allow first element trigger only when current pos is 0
            (!isFirstTrigger && found)
          ) {
                this.triggerFound = true;
                this.triggerName = trigger;
                break;
            }
        }
    }

【问题讨论】:

  • 意味着native 未定义...?
  • const extractedString = value ? value.substr(currentPos - triggerLen + 1, triggerLen) : null

标签: javascript angular


【解决方案1】:

你在你的 console.log 上得到了什么

console.log("=== native dropdown", native) ?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 2021-08-05
    • 2023-03-11
    • 2022-01-15
    • 2021-12-31
    • 2021-12-13
    • 2021-11-28
    相关资源
    最近更新 更多