未捕获的TypeError:无法读取LayoutGapStyleBuilder.buildStyles上未定义的属性'endsWith'

时间:2020-02-11 18:32:46

标签: angular typescript

将Angular 8应用程序升级到Angular 9之后,我在浏览器中针对一个模板收到以下错误:

Uncaught TypeError: Cannot read property 'endsWith' of undefined
    at LayoutGapStyleBuilder.buildStyles (flex.js:233)
    at DefaultLayoutGapDirective.addStyles (core.js:492)
    at DefaultLayoutGapDirective.updateWithValue (flex.js:434)
    at MediaMarshaller.updateElement (core.js:3189)
    at SafeSubscriber._next (core.js:3294)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
    at SafeSubscriber.next (Subscriber.js:122)
    at Subscriber._next (Subscriber.js:72)
    at Subscriber.next (Subscriber.js:49)
    at MergeMapSubscriber.notifyNext (mergeMap.js:72)
    at InnerSubscriber._next (InnerSubscriber.js:11)
    at InnerSubscriber.next (Subscriber.js:49)
    at Subject.next (Subject.js:39)
    at MutationObserver.<anonymous> (flex.js:493)
    at ZoneDelegate.invoke (zone-evergreen.js:365)

2 个答案:

答案 0 :(得分:3)

要捕获未定义的布局间隙值,请实施自定义的布局间隙构建器,以转换未定义的间隙值,例如:

import { Injectable, NgModule } from '@angular/core';
import {
  StyleBuilder,
  StyleDefinition,
  LayoutGapParent,
  LayoutGapStyleBuilder,
} from '@angular/flex-layout';

@Injectable()
export class CustomLayoutGapStyleBuilder extends LayoutGapStyleBuilder {
  buildStyles(gapValue: string, parent: LayoutGapParent): StyleDefinition {
      return super.buildStyles(gapValue || '0 px', parent);
  }

  sideEffect(gapValue, _styles, parent) {
      return super.sideEffect(gapValue || '0 px', _styles, parent);
  }

}

并在@NgModule中将其提供给您的应用程序:

@NgModule({
  //...
  providers: [
    //...
    { provide: LayoutGapStyleBuilder, useClass: CustomLayoutGapStyleBuilder },
  ],
})

答案 1 :(得分:2)

我在使用以下方法时遇到了同样的问题:

角度8.0.0
Flex-layout 8.0.0-beta.27

我的模板具有以下顶级div:

<div fxLayout="column" fxLayout.gt-xs="row wrap" fxLayoutAlign.gt-xs="start" fxLayoutGap.gt-xs="20px">

请注意,仅定义了 fxLayoutGap.gt-xs

当在Chrome上模拟移动屏幕(超小屏幕)时,然后尝试隐藏嵌套在我的顶级div下的div(使用* ngIf),则会引发相同的错误。屏幕大于特小(gt-xs)时没有问题

我认为为fxLayoutGap定义断点别名(例如gt-xs)而不是为默认值定义时会发生错误。不知道您是否确实是这种情况,而没有看到模板html。

但是,对我而言,最简单的解决方法是将 fxLayoutGap =“ 0px” 作为默认值添加到div。这为我解决了Cannot read property 'endsWith' of undefined错误。

例如

<div fxLayout="column" fxLayoutGap="0px" fxLayout.gt-xs="row wrap" fxLayoutAlign.gt-xs="start" fxLayoutGap.gt-xs="20px">