0

This was asked in an interview.

Requirement is to create a custom pipe that would return a shortened text suffixed by a 'Read more' link for a text if it has more than a certain number of characters, lets say 10 characters.

If clicked on the 'Read more' link, the entire original text should be displayed suffixed by a 'Read less' link. If clicked on the 'Read less' link, again the shortened text should be displayed suffixed by a 'Read more' link. Thus, 'Read more' and 'Read less' links and short and original text should toggle on click of the links.

This entire functionality is to be implemented by a pipe only. Is event handling possible in a pipe? How we can handle events for the clicks on the links in the pipe?

Abhinandan Khilari
  • 947
  • 3
  • 11
  • 26
  • 1
    No. A pipe is not the right tool for this job. A component is. – JB Nizet Dec 13 '19 at 07:11
  • It's possible. But quite tricky! Helpful link: https://github.com/danrevah/ngx-pipes/blob/master/src/pipes/string/shorten.ts – Surjeet Bhadauriya Dec 13 '19 at 07:17
  • https://stackoverflow.com/questions/40718823/angular2-add-read-more-link-to-custom-pipe – Surjeet Bhadauriya Dec 13 '19 at 07:18
  • I don't know. That is quite too much logic for a pipe. Since it was an interview, maybe they wanted you to challenge and wanted to see if you can find arguments against. – MoxxiManagarm Dec 13 '19 at 08:08
  • I think the ideal approach for this would be combination of a pipe for mutating the text and event handling in component for deciding whether to shorten or expand the text, by maintaining a flag for it. This flag can be passed as a parameter to the pipe to shorten or expand the text accordingly. But I think this is not scalable. If there are multiple such pipes in the same template then there can be side-effect of one pipe to the other while mutating the text. – Abhinandan Khilari Dec 13 '19 at 08:22
  • There is a good article about pipes applications https://www.lucidchart.com/techblog/2017/11/08/5-usage-ideas-for-angular-pipes/ – Timothy Dec 13 '19 at 09:01

1 Answers1

1

I think the interviewer doesn't know the actual use of a pipe. Basically a pipe shouldn't handle like these kinds of complex operations. A pipe should handle some basic operations like

  • Changing date time to locale
  • Trim the string
  • sorting the numbers based upon conditions etc.,

The best choice would be using a Shared Component. He can use this to communicate events between the components.

Suhas Parameshwara
  • 1,344
  • 7
  • 15