angular - create a new line on HTML - html

I have a simple question (I hope this). I have a service that return a string as result. The format is something like this:
"
Test1: the association has been accepted.\nTest2: the association has been accepted.\n"
"
On the client side (I'm using Angular 1.5.x) I put that string into a object (say the variable $scope.alert.message). After that I want to print that string in a modal. My html is:
<script type="text/ng-template" id="infoTemplate.html">
<div class="modal-header left" ng-class="['div-' + alert.type, closeable ? 'alert-dismissible' : null]">
<h3 class="modal-title" id="modal-title">Info</h3>
</div>
<div class="modal-body" id="modal-body">
<img class="imm-info" ng-class="['imm-' + alert.type, closeable ? 'alert-dismissible' : null]" />
<p class="col-sm-10 col-sm-offset-2">{{alert.message}}</p><button class="col-sm-3 col-sm-offset-5 btn " ng-class="['button-' + alert.type, closeable ? 'alert-dismissible' : null]" ng-click="cancel()">OK</button>
</div>
</script>
You can see the '{{alert.message}}'. My problem is that my message "doesn't display" the character '\n'. So it doesn't create more than one line. An example here:
example

I use the white-space: pre-wrap CSS style, e.g. :
<p style="white-space: pre-wrap">{{alert.message}}</p>

Try this in HTML:
<pre>{{ alert.message }}</pre>
Already answered here:
The < pre > wrapper will print text with \n as text

\n is not interpreted in html. You need to replace these instances with <br/> elements. You could for example replace them with a regex if you do not want to change the original string.

You can write a function where you take the alert-message and split it by "\n"
than iterate trough it via *ngFor.
For example:
<p *ngFor="let msg of getMessageSplitted(alert.message)">{{msg}}</p>

Related

Angular ignoring special characters

I'm trying to display a file name but when the name contains special characters it's completely ignored.
This is the code:
<p class="meta-description" [innerHTML]="{{ vm.previewing.filename + ' | ' + vm.previewing.emailSubject }}">
{ vm.previewing.filename }}
<span ng-if="vm.previewing.emailSubject"> | {{ vm.previewing.emailSubject }}</span>
Even adding [innerHTML] is not fixing the issue.
This is what shows up on the page if the file is named 'çx' for example:
<p class="meta-description ng-binding" [innerhtml]="x.pdf | ">
x.pdf
<!-- ngIf: vm.previewing.emailSubject -->
</p>
In case we are talking in AngularJS ,
Do you have the module angular-sanitize enabled ? If so use the ng-bind-html directive to parse special characters or markup to display. Also avoid mixing interpolation and property binding, choose only one to use.
<p class="meta-description" ng-bind-html="vm.previewing.filename + ' | ' + vm.previewing.emailSubject">
<span ng-if="vm.previewing.emailSubject" ng-bind-html="'|'+ vm.previewing.emailSubject"> </span>
A tip to make the code cleaner would be creating those string values on the controller side (like the concatenation of filename and email subject to the p element).
Please bear in mind that the bracket syntax "[]" is for Angular 2-11 property binding and not AngularJS.
Reference:
https://docs.angularjs.org/api/ng/directive/ngBindHtml

Why don't the String values get displayed as HTML tags using innerHTML?

I get string data from my database to my variable, I want to display them as HTML tags by [innerHTML], but it doesn't work.
The variable is displayed on string instead HTML Tags.
I tried to use with DomSanitizer but it don't work:
article:Article[];
(article.articlesTitleHtml:SafeHtml;)
in the function:
this.article.forEach(elementArticle => {
elementArticle.articlesTitleHtml = this.sanitizer.bypassSecurityTrustHtml(elementArticle.articleTitle)
});
in HTML page:
<div *ngFor="let item of articles">
<div id="{{item.articleId}}">
<h2 class="chart" [innerHTML]="item.articlesTitleHtml"></h2>
</div>
my code:
in Type Script:
articles:Article[];
ngOnInit() {
this.apiArticle.getArticleList().subscribe(data=>{
this.articles=data
})
in HTML page:
<div *ngFor="let item of articles">
<div id="{{item.articleId}}">
<h2 class="chart" [innerHTML]="item.articleTitle"></h2>
</div>
</div>
It should work, you can check here...
if you can share the type of data that you're dealing with, it will give more insight into the appropriate DomSanitizer method which should be called
in my example above, i used both bypassSecurityTrustHtml & bypassSecurityTrustUrl for the 2 different types of strings which needed sanitization

I need CSS selector to select elements that contain a given text

Line:
<div class="btn btn-second-in-pair-not-desired btn-tall">Clear search</div>
<div class="btn btn-second-in-pair-not-desired btn-tall">Raw Search</div>
<div class="btn btn-second-in-pair-not-desired btn-tall">Basic Search</div>
<div class="btn btn-primary-stand-alone btn-tall search-btn">Search</div>
Here is what i have tried so far -
".btn:contains('Clear search')" but selenium is not able to catch it
CSS Selector doesn't support :contains() anymore. You have to use XPath "//div[text()='Clear search']".
I don't think css supports searching by content of the html element.
Why not try:
<div class="btn btn-second-in-pair-not-desired btn-tall clear">Clear search</div>
<div class="btn btn-second-in-pair-not-desired btn-tall raw">Raw Search</div>
<div class="btn btn-second-in-pair-not-desired btn-tall basic">Basic Search</div>
<div class="btn btn-primary-stand-alone btn-tall search-btn">Search</div>
And then selecting via:
.btn{
color:red;
}
.clear, .raw, .basic, .search-btn{
color:blue;
}
Or you could always try using ids
<div id="search">Search</div>
select:
#search{
...
}
If your using Selenium, it also accepts XPATH strings, which can sometimes be more flexible than CSS Selectors in some instances. Because I'm super lazy as well, I find it quite handy that you can right click a tag in the Elements view of DevTools and "Copy > Copy XPath"
webDriver.findElement(
By.xpath(
"//div[text()='Clear search']"
)
).click();
you cannot change the class depending on the content ?
<?php
$content = $your_content_from_database;
$arr_content = explode(" ", $content);
$first = $arr_content[0];
echo '<div class="btn btn-second-in-pair-not-desired btn-tall clear" data-content="'.$first.'">'. $content. '</div>' ; ?>
and the CSS
[data-content="Clear"]{
color:red;
}
Hi on the basis of the source provided by you in the question you can use css selector as below to identify the elements
// take everything inside the list for div with same class
List<WebElement> mycsselements = driver.findElements(By.cssSelector(".btn.btn-second-in-pair-not-desired.btn-tall"));
System.out.println("Size of the div elements with same class name : " + mycsselements.size());
// printing value one by one
System.out.println("First value is " + mycsselements.get(0).getText());
System.out.println("Second value is " + mycsselements.get(1).getText());
System.out.println("Third value is " + mycsselements.get(2).getText());
// and for the last one do it like below
System.out.println("Last value is " + driver.findElement(By.cssSelector(".btn.btn-primary-stand-alone.btn-tall.search-btn")).getText());
and the output is :
Size of the div elements with same class name : 3
First value is Clear search
Second value is Raw Search
Third value is Basic Search
Last value is Search
Hope this helps you
User below css code:
css=div:contains('Clear search')
More details click on link: SauceLab

Get div class title content text using xpath

I have a requirement of getting the text below of "ELECTRONIC ARTS" (this can change according to data) using class title "Offered By" (this class will be same for all) using Xpath. I tried various xpath coding, but couldn't get the results I want. I'm really looking for someone's help on this.
<div class="meta-info">
<div class="title"> Offered By</div>
<div class="content">ELECTRONIC ARTS</div> </div>
This is one possible XPath expression to starts with, which then you can simplify or add more criteria as needed (XPath formatted to be more readable) :
//div[
#class='meta-info'
and
div[#class='title' and normalize-space()='Offered By']
]/div[#class='content']
explanation :
//div[#class='meta-info' and ... : find div element where class attribute value equals "meta-info" and ...
div[#class='title' and normalize-space()='Offered By']] : ... has child element div where class attribute value equals "title" and content equals "Offered By"
/div[#class='content'] : from such div (the <div class="meta-info"> to be clear), return child element div where class attribute value equals "content"
Using the examples on Mozilla:
var xpath = document.evaluate("//div[#class='content']", document, null, XPathResult.STRING_TYPE, null);
document.write('The text found is: "' + xpath.stringValue + '".');
console.log(xpath);
<div class="meta-info">
<div class="title"> Offered By</div>
<div class="content">ELECTRONIC ARTS</div>
</div>
By the way, I think document.querySelector or document.querySelectorAll are much more convenient in this situation:
var content = document.querySelector('.meta-info .content').innerText;
document.write('The text found is: "' + content + '".');
console.log(content);
<div class="meta-info">
<div class="title"> Offered By</div>
<div class="content">ELECTRONIC ARTS</div>
</div>

How to get a single text node in Selenium WebDriver [duplicate]

This question already has answers here:
Getting text from a node
(5 answers)
Closed 5 years ago.
I want to get the text from a tag but without the text from nested tags. I.e. in the example below, I only want to get the string 183591 from inside the <small> tag and exclude the text Service Request ID: from the <span> tag. This is not trivial because the <span> tag is nested in the <small> tag. Is this possible with WebDriver and XPath?
The text in the tag is going to change every time.
<div id="claimInfoBox" style="background-color: transparent;">
<div class="col-md-3 rhtCol">
<div class="cib h530 cntborder">
<h4 class="no-margin-bottom">
<p>
<small style="background-color: transparent;">
<span class="text-primary" style="background-color: transparent;">Service Request ID:</span>
183591
</small>
</p>
<div class="border-bottom" style="background-color: transparent;"></div>
<div id="CIB_PersonalInfo_DisplayMode" class="cib_block">
<div id="CIB_PersonalInfo_EditMode" class="cib_block" style="display: none">
</div>
</div>
<script type="text/javascript">
</div>
</div>
You are going to have to use String manipulation. Something like:
// you will need to adjust these XPaths to suit your needs
String outside = driver.findElement(By.xpath("//small")).getText();
String inside = driver.findElement(By.xpath("//span")).getText();
String edge = outside.replace(inside, "");
The simplest way I've found is by getting the parent small node and the child span node and removing the number of characters in the child from the text of the parent:
public String getTextNode() {
WebElement parent = driver.findElement(By.xpath("//small")); //or By.tagName("small")
WebElement child = parent.findElement(By.xpath(".//span")); //or By.tagName("span")
return parent.getText().substring(child.getText().length()).trim();
}
The actual simplest way is using javascript executor as below:
JavascriptExecutor js = ((JavascriptExecutor)driver);
js.executeScript("return $(\"small\").clone().children().remove().end().text();");
This will return the text associated with the parent element 'small' only. Use trim() to omit leading and trailing whitespace. For the full explanation of what is happening here, please refer the link below.
Reference:
http://exploreselenium.com/selenium/exclude-text-content-of-child-elements-of-the-parent-element-in-selenium-webdriver/