Angular页面调试一个有用的小技巧 - normalizeDebugBindingName和normalizeDebugBindingValue

时间:2022-07-26
本文章向大家介绍Angular页面调试一个有用的小技巧 - normalizeDebugBindingName和normalizeDebugBindingValue,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在开发模式下渲染出的Angular页面包含了很多形如下图ng-reflect-的html属性,很多时候其值都为[object Object].

如果处于调试目的,需要在Chrome开发者工具里观察这些值的具体内容,可以采取本文介绍的一个小技巧:

在下列两个函数里设置断点:

  • normalizeDebugBindingName
  • normalizeDebugBindingValue
function normalizeDebugBindingName(name) {
    // Attribute names with `$` (eg `x-y$`) are valid per spec, but unsupported by some browsers
    name = camelCaseToDashCase(name.replace(/[$@]/g, '_'));
    return `ng-reflect-${name}`;
}
const CAMEL_CASE_REGEXP = /([A-Z])/g;
function camelCaseToDashCase(input) {
    return input.replace(CAMEL_CASE_REGEXP, (...m) => '-' + m[1].toLowerCase());
}
function normalizeDebugBindingValue(value) {
    try {
        // Limit the size of the value as otherwise the DOM just gets polluted.
        return value != null ? value.toString().slice(0, 30) : value;
    }
    catch (e) {
        return '[ERROR] Exception while trying to serialize the value';
    }
}

运行时,我们就可以在调试器里观察到变量的具体值了: