Adding line breaks when using interpolation - javascript

I have some html for an alert message box. Using interpolation, I can re-use the same html to show multiple different alert messages. It looks like this: <p>{{ myAlertMessage }}</p>
Now I want to show a longer alert message containing line breaks. However, I cannot seem to modify the interpolated component property (which is a string) in any way which will introduce line breaks.
For example, using </br>, or spacing the text across several lines in the component code (contained in either parentheses or back ticks), or the new line code (
). None of these work to produce a line break in the text when the alert message is shown.
I would prefer not to have to add further property bindings just to cater for this particular use case.
Thanks in advance.

Just use
<span [innerHTML]="myAlertMessage"></span>
the innerHTML property will interpret your html code.

The solution, for Angular v2.1.1 at least, is to use [innerHTML]="myAlertMessage". It isn't necessary to use "bypassSecurityTrustHtml" for line breaks or lists to work.

You can use a pipe like
import { Pipe, Sanitizer } from '#angular/core';
#Pipe({name: 'safe'})
export class SafeHtml {
constructor(private sanitizer:Sanitizer){}
transform(html) {
return this.sanitizer.bypassSecurityTrustHtml(html);
}
}
and use it like
<span [innerHTML]="myAlertMessage | safe"></span>
where myAlertMessage can contain <br> or <p>
See also In RC.1 some styles can't be added using binding syntax

Try to use \n in your myAlertMessage text.
Something like that: "\n Some alert text \n Newline of the alert text";
And use a <pre> html tag in your component HTML file like that:
<div>
<p><pre>{{ myAlertMessage }}</pre></p>
</div>

Related

Is it possible truncate excerpt with DOM atributtes? HTML/JS

I have tried to shorten excerpt from Wordpress REST API, I've tried maxLength HTML attribute, but it does not work.
<p
dangerouslySetInnerHTML={{ __html: excerpt.rendered }}
maxLength={10}
/>
Is there any way I can handle it within JS/React?
Thanks in advance
Your question hardly has anything to do with React, it's more about html.
HTML's maxlength attribute is applicable only to input and textarea tags, this way it will do nothing when applied to p tag.
HTML doesn't have anything similar for p natively, so, a custom implementation is needed. You obviously could do:
'Long text of the article that is going to be shortened'.slice(0, 9).concat('…')
which would produce Long text….
However, since you use dangerouslySetInnerHTML, I guess that excerpt.rendered contains HTML tags, so, you can't just slice it.
In this case, the easiest option would be to have 2 strings:
One containing ready-to-use markup.
One containing just text content.
If it's not an option, you may try to parse HTML & extract only text content (be cautious, it might produce unexpected results):
const parsedExcerpt = new DOMParser().parseFromString(excerpt.rendered, 'text/html');
const excerptText = parsedExcerpt.body.innerText.trim();
Now you could use excerptText.slice(0, 9).concat('…') (more or less) safely.

How can i modify downloaded html in an ionic app?

I'm new to ionic, we're trying to build a reader app that downloads documents in html from a service and then displays them. I know how to modify html that is part of the ionic application itself, but the documents we download are displayed inside the ionic app. We want to add a search function that finds and highlights all occurrences of the entered words. We find them and highlight them by wrapping them in a span that has a css class that sets a yellow background. But it doesn't reflect the changes in the app.
The document is downloaded from the service and then wrapped in a div, here's what we have do far, this is a snippet from the document.html for the document page in the app and is where the downloaded content lives:
<ion-content id="content">
<div [ngClass]="isNight ? 'night' : 'day'">
<div [ngClass]="isSingle ? 'single' : 'double'">
<div id="inputText" class="document" [innerHtml]="document | keepHtml" [ngStyle]="{'font-size': fontSize+'em' }"></div>
</div>
</div>
</ioncontent>
The javascript that highlights the hits is, I've left out the search box stuff since it's really just boilerplate, the highlight method is where the problem lies:
highlight(keyword) {
var inputText = document.getElementById("inputText");
var innerHTML = inputText.innerHTML;
inputText.innerHTML = innerHTML.replace(new RegExp(keyword, 'g'), "<span class=\"keyword\">" + keyword + "</span>");
}
If the user searched for "the", for example, after the highlight() method runs we should see every "the" in the document highlighted in yellow. But we don't. If we remove the "| keepHtml" from the div for the document, search works.
If we display the document html using an alert from the typescript method we see our changes, but if we run the javascript console in the browser and look at the html in the Dom of the browser, the changes we made are not there.
I know I'm missing something obvious or fundamental to ionic/angular but so far I can't see what it is. Maybe I'm so far off that nobody can help me but I thought I'd take a shot. Thanks for understanding.
Adding the keepHtml code:
import { Pipe, PipeTransform } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
/**
* Generated class for the KeepHtmlPipe pipe.
*
* See https://angular.io/api/core/Pipe for more info on Angular Pipes.
*/
#Pipe({ name: 'keepHtml', pure: false })
export class KeepHtmlPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {
}
transform(content) {
return this.sanitizer.bypassSecurityTrustHtml(content);
}
}
We discovered the problem; ionic/angular thought our html was unsafe. We started sanitizing it before we added it back in and it works.
We actually found two solutions, one was to run a sanitizer in the page class (excuse me if my angular-speak is not quite right, I've lived through so many "Waves of the Future" that at this point in my career they're all starting to run together) with bypassSecurityTrustHtml and the other, surprisingly was to add the modified HTML back into this.document instead of element.innerHTML.
The second solution seems like black magic, I'm not sure I understand why it works. I actually prefer the first solution.

jQuery - How to format readable HTML syntax?

I want to generate HTML code. The result is injected into a textarea. Afterwards a user can simply copy the result code. My problem is that the generated HTML code has no tabs and linebreaks, making it hard to read.
js fiddle
I want it to look like that:
HTML
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Just add a \n to the end of each line:
http://jsfiddle.net/9NCvd/3/
Note: You can add tabs. just use \t
You can't. That would take HTML to format, and HTML does not render inside of a textarea. If you want formatting, ditch the textarea and use something else.
Edit: I lied. You just have to insert line breaks \n where you want a new line.
You can't add tabs, but you can use \n after each line for line breaks and you can simulate tabs with (two or four) spaces.
I think you are trying to do something like: http://jsfiddle.net/hvuLU/
there is a decode function i created.
function myDecode(s){
return s.replace(/\</g,"<").replace(/\>/g,">");
}
This here, would allow you to do something like:
Paste into textbox to render in a box below it. Sort of how Stackoverflow has its textarea and then the render area.

Declaring a parameter in html and receiving it in Javascript

My js function goes like this:
function tester (message) {
alert(message);
}
And in the markup I have:
Link
But it doesn't work. Can someone please tell me why?
text to show is not a string unless you wrap it with quotes, either single or double.
Like this:
Link
Notice that you can't use the same kind of quote for both the Javascript code and the HTML.
Your code is probably giving errors. Check the console when the code doesn't do what you expect it to.
You are almost there. All you have to do is wrap text to show in quotes, like this:
Link
What's happening here is that you have an <a> tag with two attributes, href and onclick. In the href you write the URL that the link points to. In the onclick attribute, you write Javascript. The Javascript here is:
tester('text to show');
which runs a function called tester, passing it the string 'text to show'. Your original code had Javascript like this:
tester(text to show);
which results in a Syntax Error. As an aside, if you had Javascript like this:
tester(text);
it would have looked for a variable named text, and if this variable was defined, you would get an alert with that text.
One more thing: when you include text inside HTML attributes, like you did here, you should be careful not to use the same quotes you used to enclose the attribute. That is why we used single quotes. Suppose you wanted to use double-quotes or other fancy characters, such as the © symbol ... then you replace them with their "HTML-escaped" value, in this case ©. Click here for some common values.

CKEditor setData adding P tag

When i am passing HTML to a CKEditor instance, a P tag is being inserted within the HTML producing unexpected results.
For example, with the following code:
CKEDITOR.instances["myEditor"].setData("<div>1</div><div>2</div>");
the editor does not display them as block elements (it outputs as "12" inline). Calling getData() and i see the HTML is reformatted incorrectly as:
"<div>
<p>
1</div><div>2</div></p>
"
I've played with the enterMode configuration based on some research but haven't found a magic combination. Any suggestions? (I am using 3.6.5)
I figured it out - we we're using regex to strip out some tags when pasting and this was also impacting initial values.

Categories

Resources