Apply Angular Pipe to Angular Recursive List template

263 Views Asked by At

I have a recursive Angular template using Pipe for deeply nested array of objects where I have data and children. My problem is it only that when using search function I'm using pipe that highlights the searched and found data in the nested object. The DomSanitizer works but it doesnt bypass security and I get SafeValue must use [property]=binding. I tried using it as [innerHtml]="item.data | search:searchedData" but I'm getting only top values and not the deeply nested child values.

HTML Template that I'm using for rendering the nested data.

<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>

The pipe that I'm using for highlighting the searched data.

@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);
  }
}

The html value that I'm getting:

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)
1

There are 1 best solutions below

0
On BEST ANSWER

I fixed it by using another span element inside li ngfor and apply the values with innerHtml, since ngfor elements are still not ready for using pipe.

The following code fixed the issue that I had:

<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>