【问题标题】:Apply Angular Pipe to Angular Recursive List template将 Angular Pipe 应用于 Angular 递归列表模板
【发布时间】:2020-09-07 14:08:18
【问题描述】:

我有一个使用 Pipe 的递归 Angular 模板,用于深度嵌套的对象数组,其中我有数据和子对象。我的问题是,只有在使用搜索功能时,我使用的管道会突出显示嵌套对象中搜索和找到的数据。 DomSanitizer 有效,但它没有绕过安全性,我得到 SafeValue 必须使用 [property]=binding。 我尝试将其用作 [innerHtml]="item.data | search:searchedData" 但我只得到最高值而不是深度嵌套的子值。

我用于呈现嵌套数据的 HTML 模板。

<h1>Angular Recursive List</h1>
<ul>
  <ng-template #recursiveList let-users>
    <li *ngFor="let item of users">
      {{item.data  | search:searchedData}}
      <ul *ngIf="item.children.length > 0">
        <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: item.children }">
        </ng-container>
      </ul> 
    </li>
  </ng-template>
  <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: users}"></ng-container>
</ul>

我用来突出显示搜索数据的管道。

@Pipe({
  name: 'search',
})
export class Search implements PipeTransform {
  constructor(private sanitizer: DomSanitizer){}
  transform(value: any, args: any): any {
    if (!args) {
      return value;
    }
    const val = new RegExp(args, 'gi');
    const domElement = value.replace(val, `<mark>${args}</mark>`);
    return this.sanitizer.bypassSecurityTrustHtml(domElement);
  }
}

我得到的 html 值:

SafeValue must use [property]=binding: Person 1(see http://g.co/ng/security#xss)
  SafeValue must use [property]=binding: State(see http://g.co/ng/security#xss)
    SafeValue must use [property]=binding: City(see http://g.co/ng/security#xss)
     SafeValue must use [property]=binding: Street(see http://g.co/ng/security#xss)
SafeValue must use [property]=binding: Person 2(see http://g.co/ng/security#xss)
  SafeValue must use [property]=binding: <mark>State 2</mark> (see http://g.co/ng/security#xss)
   SafeValue must use [property]=binding: City(see http://g.co/ng/security#xss)

【问题讨论】:

    标签: angular pipe angular-dom-sanitizer


    【解决方案1】:

    我通过在 lingfor 中使用另一个 span 元素来修复它,并使用 innerHtml 应用值,因为 ngfor 元素还没有准备好使用管道。

    以下代码解决了我遇到的问题:

    <h1>Angular Recursive List</h1>
    <ul>
      <ng-template #recursiveList let-users>
        <li *ngFor="let item of users">
          <span [innerHtml]="item.data  | search:searchedData"></span>
          <ul *ngIf="item.children.length > 0">
            <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: item.children }">
            </ng-container>
          </ul> 
        </li>
      </ng-template>
      <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: users}"></ng-container>
    </ul>
    

    【讨论】:

      猜你喜欢
      • 2015-09-11
      • 2017-06-15
      • 1970-01-01
      • 2019-05-24
      • 1970-01-01
      • 2018-11-11
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多