【问题标题】:Custom Angular directive is not working with async value自定义 Angular 指令不适用于异步值
【发布时间】:2020-06-23 13:03:30
【问题描述】:

我们的项目中有一个自定义指令,当我们想要修剪某些 UI 元素中的长文本时使用它。在一种情况下,它无法正常工作。没有错误,没有警告,只是不存在。检查 DevTools 中的代码没有显示该指令触发的迹象(没有 HTML 更改,没有添加 CSS)。该指令如下所示:

ngAfterViewInit() {
  let text = <string>this.elt.nativeElement.innerHTML.trim();
  if (!text || text !== (<HTMLElement>this.elt.nativeElement).innerText) {
    return;
  }

  const limit = this.value || DEFAULT_VISIBLE_ENDING_LENGTH; // default length = 4
  if (text.length > limit && this.elt.nativeElement.scrollWidth > this.elt.nativeElement.clientWidth) {
    const startText = text.substr(0, text.length - limit);
    const endText = text.substr(-limit);
    this.renderer.setProperty(
      this.elt.nativeElement,
      'innerHTML',
      `<div class="part1"><span>${startText}</span></div><div class="part2"><span><span>${endText}</span></span></div>`
    );
  }
}

当要显示和修剪的文本是从可观察的(存储选择器)获得时,它无法工作。不管我是使用Observable + async 管道还是将值映射到选择器订阅中的组件属性。

@Component({
  ...
  changeDetection: ChangeDetectionStrategy.OnPush,
})

this.sampleInProgress$: Observable<string>;
this.sampleInProgress: string;
...
this.sampleInProgress$ = this.store.select(fromAutomation.getInfoPanelData).pipe(
  map(({ sample, experiment }) => {
    this.sampleInProgress = sample?.sampleName; // does not work either
    this.experimentInProgress = experiment?.parameterSet;
    return sample?.sampleName;
  }),
);

还有 HTML:

<span class="label" gs-ellipsis>{{ sampleInProgress$ | async }}</span>
<!-- In this case, subscribe is done in the component -->
<span class="label" gs-ellipsis>{{ sampleInProgress }}</span>

抱歉,代码有点乱,我只是不想两次发布几乎相同的代码。我要么明确订阅,要么使用async 分配可观察对象。不要同时做这两件事。代码中我们使用此省略号的其他地方(以及它的工作原理)也使用OnPush 检测策略,但该值由@Input 提供。

我感觉它与指令本身中的ngAfterViewInit() 有关,但我不确定。指令不是我最擅长的领域。

知道可能是什么原因以及如何解决它吗?

【问题讨论】:

    标签: html angular typescript


    【解决方案1】:

    您的指令处理发生得太早了。我假设您可以在 ngIf 指令的帮助下稍微修改一下并在其内容正常时渲染元素。

    <span class="label" gs-ellipsis *ngIf="sampleInProgress$ | async as value">{{ value }}</span>
    

    【讨论】:

      猜你喜欢
      • 2016-07-14
      • 2016-05-30
      • 2019-10-01
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多