0

I am creating an application where I have placed a Textarea, now my requirement is I have a list of words and so whenever i will type anything in textarea if words matches from the available list it will be highlighted with color backgraoud , I was looking for this solution in Angular2 but won't get anything. If any one can suggest any plugin.

Bijay Kumar Rai
  • 77
  • 1
  • 10

1 Answers1

0

How about angular text input highlight ?

npm link: https://www.npmjs.com/package/angular-text-input-highlight

Simply reference your with template reference variable, #textarea

<textarea
    mwlTextInputElement
    [(ngModel)]="text"
    #textarea>
</textarea>

and then pass reference into their highlight component.

<mwl-text-input-highlight
    [tags]="tags"
    [textInputElement]="textarea">
</mwl-text-input-highlight>

the Tags input take in an array of tag object, here is a function that will find the indexes, from How to find indices of all occurrences of one string in another in JavaScript?

function getIndicesOf(searchStr, str, caseSensitive) {
var searchStrLen = searchStr.length;
if (searchStrLen == 0) {
    return [];
}
var startIndex = 0, index, indices = [];
if (!caseSensitive) {
    str = str.toLowerCase();
    searchStr = searchStr.toLowerCase();
}
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
    indices.push(index);
    startIndex = index + searchStrLen;
}
return indices;
}

and now to get the tag object, we can use following function, which return a list of tag object.

function GetTagObject(searchstr, str, caseSensitive, cssClass) {
  const startingIndices = getIndicesOf(searchstr, str, caseSensitive);

  return startingIndices.map((index) => {
     return {
    indices: {
      start: index,
      end: index + searchstr.length
    },
    cssClass: cssClass,
    data: searchstr
  }
  })
}

now all you need to do is to use loop (reduce) through your string array and run the function from above.

const text = "Stackoverflow is awesome! Perfect! awesome!";
const matchText = ["awesome", "perfect"];

const result = matchText.reduce((acc, cur) => 
  acc.concat(GetTagObject(cur, text, false, "red"))
, []);
Ringo
  • 601
  • 5
  • 14
  • I have used it and i did following Steps its showing textarea but it isn't highlighting the text. I have follow the documentation. – Bijay Kumar Rai Jan 04 '18 at 05:51
  • It is now working correctly , Can we pass an array of string in tag list so that we can highlight our predefined words , Instead of using delimiter. – Bijay Kumar Rai Jan 04 '18 at 07:28
  • looks like they require an array of tag object, which includes the tag, css class and the string itself. updated my original answer to include a function that will get the object for you from a list of string – Ringo Jan 04 '18 at 15:09