Angular 8 - ngxTextHighlight

Asked

Viewed 67 times

-1

Expensive,

I’m starting with Angular now and it’s been a long time since I developed for front-end. And I’m having some doubts that I’d like to ask the community for help.

So come on.

I have a page where the data is loaded by the main Komponent. This main Component, mounts a treeview to the left side, where, when clicking on some treeview ode the data corresponding to the clicked item are loaded to the right side, inside a div content, loaded by the search Component. This search component has an input text, which has the purpose of searching words within the content and highlighting them. This is working perfectly, however, by typing a word that does not exist or deleting the content of the search field, the data of the div where the content is displayed will display the data between the html tags and when writing to an existing word it returns the formatted content.

I’m beginning to understand the mechanism of the thing. I already know that Angular works with modules and is componentized and that the components can talk to each other exchanging data. Well, the main component it consumes a web API and loads the database data, dynamically, it defines where each data will be loaded. In this specific case, it passes the content data to the search component. But the moment I enter some value that does not exist in the search input it loses the content passed by the main component.

I believe that for someone who knows the technology well it should be something simple to solve.

Below is the excerpt from the above components codes:

import { Component, OnInit, Input,Output,EventEmitter, SimpleChanges, OnChanges, ChangeDetectionStrategy } from '@angular/core';
import { ItemExame, IgResult, Instrucoes } from '../IGInstrucoes';
import { DataServiceService } from 'src/app/data-service.service';
import { NodeClickEventArgs, NodeKeyPressEventArgs } from '@syncfusion/ej2-navigations';
import { Router } from '@angular/router';


@Component({
  selector: 'ig-principal',
  templateUrl: './principal.component.html',
  styleUrls: ['./principal.component.css'],

  //changeDetection: ChangeDetectionStrategy.OnPush
})
export class PrincipalComponent implements OnInit , OnChanges{
  order: string = 'nodeChild';
  reverse: boolean = false;

 ngOnChanges(changes: SimpleChanges) {
  //console.log(changes)
  changeDetection: ChangeDetectionStrategy.OnPush
}

  igResult : IgResult;
  @Input() conteudo = "";
  conteudo_auxiliar: string;
  @Output() messageEvent = new EventEmitter<string>();

  showSpinner: boolean = true;
  public treeFields: Object;
  sortedCollection: any[];
  
  constructor(private data: DataServiceService)  {  alert('constructor - principal')}
  //constructor(private router: Router,private dataService: DataServiceService)  {  }
  
  CarregaNodes()
  {
    this.data.getList().subscribe((res) => {
      this.igResult = res;
      this.treeFields =
      {
        dataSource: this.igResult.nodes ,
        id: 'id',
        text: 'description',
        child: 'nodeChild'
        };
      });

  }

  ngOnInit(): void {
    alert('RDN: principal.component.ts/ngOnInit');
    //alert('RDN: principal.component.ts/ngOnInit: ' + this.conteudo);
    this.CarregaNodes();
  }  

  // enable the editing options to the TreeView
  public allowEditing: boolean = true;

  //Bind the nodeChecked event
  public nodeCheck(args: NodeKeyPressEventArgs | NodeClickEventArgs| any): void {

    //Recupera os Ids
    let checkedNode: any = [args.node.dataset];

    let ids: string =  checkedNode[0].uid;
    alert('RDN - 1: principalcomponents/nodeCheck -> ids: ' + ids);

    let split:string[] = ids.split('-');
    alert('RDN - 2: principalcomponents/nodeCheck -> split: ' + split);

    let idIg:number = Number(split[0]);
    alert('RDN - 3: principalcomponents/nodeCheck -> idIg: ' + String(idIg));

    let IgItem:number = Number(split[1]);
    alert('RDN - 4: principalcomponents/nodeCheck -> IgItem: ' + String(IgItem));

    let instrucao:Instrucoes = this.igResult.instrucoes.filter(f => f.id == idIg)[0];
    alert('RDN - 5: principalcomponents/nodeCheck -> f.id: ' + String(this.igResult.instrucoes.filter(f => f.id)[0].id));

    //instrucao.informacoesAdicionais.forEach( function(element){alert(element.linhas + '/' + element.titulo);})

    this.MontaTabelas(instrucao);

    alert('RDN - 6: principalcomponents/nodeCheck -> split.length: ' + String(split.length));
  
     if(split.length< 2){

      alert('RDN - 7: principalcomponents/nodeCheck -> split.length: IF');
      return;
    }
      
    let item: ItemExame = instrucao.descricaoItem.filter(f => f.idChave ==IgItem)[0];

    let retorno:string = '<h5>' + instrucao.description + '</h5>' + 
                         '<b>' + item.chave + '</b></br>' + item.valor + '<hr>';

    this.igResult.instrucoes.filter(f => f.id !=idIg).forEach(ig => {
      ig.descricaoItem.filter(f => f.chave ==item.chave).forEach(itemChave => {
        retorno += '<h5>' + ig.description + '</h5>' + 
                   '<b>' + item.chave + '</b></br>' + item.valor + '<hr>';
      });
    });

    let conteudo_auxiliar = retorno;
    this.conteudo = retorno;
  }

  private MontaTabelas(instrucao: Instrucoes) {

    const divRodape = document.getElementById('divRodape');
    let div: string = "<div>";
    let table: string = "";
    instrucao.informacoesAdicionais.filter(f => f.linhas.length > 0).forEach(informacao =>
    {
      "<span class='label label-default'>" + informacao.titulo + "</span>"
      informacao.linhas.forEach(linha => {
        
      table += linha;
    });
        
    div += "<b>" + informacao.titulo + "</b>";
    div += "<p class='text-justify'>" + table + "</p>";
     
    });
    div += "</div>";

    this.showSpinner = true;
    divRodape.innerHTML = div;
  }
}

<div class="container-fluid">
    <div class="row">
        <div class="col-3 border"> 
          <div class="form-check form-check-inline">
              <input class="form-check-input" type="checkbox" id="checkbox">
              <label class="form-check-label">Ordem Alfabética</label>
            </div>
            
            <div id='treeparent'>
              <ejs-treeview id='treeelement' [fields]='treeFields' (nodeClicked)="nodeCheck($event)" (keyPress)="nodeCheck($event)">
                <ig-loading-spinner *ngIf="showSpinner"></ig-loading-spinner>
                  {{ collection | orderBy: expression : reverse : caseInsensitive : comparator }}
              </ejs-treeview>              
            </div>
        </div>
        <div class="col-9 border" style="max-height: 100%; height: 700px;">
          <ig-pesquisa [actualText]='conteudo'></ig-pesquisa>
        </div>
    
        <div id="divRodape" class="col-12 border" style="height: 80px;"> </div> 
    </div>
  </div>

import { Component, OnInit, Input, OnChanges, ChangeDetectionStrategy, ElementRef, ViewChild } from '@angular/core';
import { stringify } from 'querystring';
import { PrincipalComponent } from '../principal/principal.component';
import { Router } from '@angular/router';
import { DataServiceService } from 'src/app/data-service.service';

@Component({
  selector: 'ig-pesquisa',
  templateUrl: './pesquisa.component.html',
  styleUrls: ['./pesquisa.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class PesquisaComponent implements OnInit, OnChanges
{
  @ViewChild('dataContainer') dataContainer: ElementRef;

  ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
    //debugger ;
    //console.log(changes);
    
    alert('RDN - 1: ngOnChanges -> pesquisa.component.ts');
    this.html = this.actualText;

    this.dataContainer.nativeElement.innerHTML = this.html;

    const divConteudo1 = document.getElementById('divConteudo');
    //divConteudo1.innerHTML = this.actualText;
    divConteudo1.nativeElement.innerHTML =  this.html;
    

    //alert(this.html);
  }

  @Input() html:string;
  @Input() actualText ='';
  @Input() conteudo: string;
  @Input() searchText: string;

  constructor(){
    alert('constructor - pesquisa');
    //console.log('RDN - 3: ngOnChanges -> pesquisa.component.ts');
    //alert('this.conteudo -> constructor: ' + 'constructor');
    //alert(this.html);
  }

  ngOnInit() {
    //alert('constructor - principal')
    //alert(this.html);
    //const val_pesquisa = (<HTMLSelectElement>document.getElementById('pesquisa')).value;
    alert('RDN - 2: ngOnInit -> pesquisa.component.ts');
    //alert('val_pesquisa: ' + val_pesquisa);
    //alert('this.conteudo: ' + this.conteudo.toString);

    
  }
}

 /*
ngAfterContentInit(){alert('ngAfterContentInit');}
ngAfterContentChecked(){alert('ngAfterContentChecked');}
ngAfterViewInit(){alert('ngAfterViewInit');}
ngAfterViewChecked(){alert('ngAfterViewChecked');}
ngonDestroy(){alert('ngonDestroy');}
*/

<input  class="form-control mr-sm-2"
        type="text"
        name="search"
        placeholder="Pesquisar"
        aria-label="Search" 
        value="Pesquisar"
        [(ngModel)]="searchText"
        id="pesquisa"
>
<div #dataContainer
     id="divConteudo"
     ngxTextHighlight
     [content]=html
     [searchTerm]="searchText"
     [caseSensitive]="false">
</div>

Attached are photos of the sequence of the reported facts.inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

1 answer

0

I am studying the use of behaviorsubject that seems to suit what I need. I would like to know if anyone has knowledge about?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.