Highlight the search text - angular 2

前端 未结 7 865
心在旅途
心在旅途 2020-12-01 05:22

A messenger displays the search results based on the input given by the user. Need to highlight the word that is been searched, while displaying the result. These are the h

7条回答
  •  旧巷少年郎
    2020-12-01 05:41

    One difficulty the innerHTML method has is in styling the tag. Another method is to place this in a component, allowing for much more options in styling.

    highlighted-text.component.html

    {{matched}}{{unmatched}}
    

    highlighted-text.component.ts

    import { Component, Input, OnChanges, OnInit } from "@angular/core";
    
    @Component({
        selector: "highlighted-text",
        templateUrl: "./highlighted-text.component.html",
        styleUrls: ["./highlighted-text.component.css"]
    })
    export class HighlightedTextComponent implements OnChanges {
        @Input() needle: String;
        @Input() haystack: String;
        public matched;
        public unmatched;
    
        ngOnChanges(changes) {
            this.match();
        }
    
        match() {
            this.matched = undefined;
            this.unmatched = this.haystack;
            if (this.needle && this.haystack) {
                const needle = String(this.needle);
                const haystack = String(this.haystack);
                const startIndex = haystack.toLowerCase().indexOf(needle.toLowerCase());
                if (startIndex !== -1) {
                    const endLength = needle.length;
                    this.matched = haystack.substr(startIndex, endLength);
                    this.unmatched = haystack.substr(needle.length);
                }
            }
        }
    }
    

    highlighted-text.component.css

    mark {
        display: inline;
        margin: 0;
        padding: 0;       
        font-weight: 600;
    }
    

    Usage

    
    

提交回复
热议问题