How to pass a concatenated string as a parameter to function: Angular 2 - html

I have the following code:
...
<tr ngFor= "let i = index">
<myCustomElement myName="{{'nameEdit'+i}}">
<button
<--This is where I get the "Got interpolation ({{}}) where expression was expected" error-->
(click)="myFunction(requestForm.controls.'nameEdit'{{i}}.value)">
</button>
</myCustomElement>
</tr>
...
My goal is pass to myFunction the value of nameEdit for each element (so this will be nameEdit1, nameEdit2, nameEdit3 and so on. My existing code results to an Got interpolation ({{}}) where expression was expected error.
What's the proper way to pass my value to myFunction?

(click)="myFunction(requestForm.controls['nameEdit' + i].value") should do the trick
Since double quotes for event directives (...) are interpolated, the {{ ... }} is unnecessary. You will need to also use the javascript object identifier [...] with the dynamic text.
Lastly, this will obviously return error if the controls doesn't have a key with the name you're trying to parse. It would be best practice to have myFunction(...) manage this case.
Working stackblitz example that outputs the values: https://stackblitz.com/edit/angular-whq8ll-od64hx?file=app/slider-overview-example.html

Related

How to show a particular URL to the user depending on JSON input using ngIf? (Angular)

In Angular, how to use *ngIf to check whether a JSON value includes a certain string, and then show them a certain URL ? In my case I have a object name called campaigns.description which has a value that includes a description. I want to see whether a given string, for example "one beam" is included in that description and show an URL based on that.
So not the way that the value equals a certain string, but the text that is held within the value includes a certain string.
You can use indexof() function to check the existence of some substring inside a string. This function returns '-1' if the substring is not present in the string.
<label *ngIf="campaigns.description.indexOf('One Beam') != -1 ? true : false">{{urlToShow}}</label>
You could generally use indexOf to check whether a string contains a sub-string.
console.log("Sample string".indexOf('string'));
console.log("Sample string".indexOf('not'));
The Angular part:
Trivial (not recommended)
Trivial solution is to check directly in the *ngIf condition
<div *ngIf="campaigns.description.indexOf('one beam') !== -1; else other">
<!-- contains the sub-string -->
</div>
<ng-template #other>
<!-- does not contain the sub-string -->
</ng-template>
However binding a function to *ngIf directive with default change detection strategy would trigger the function for each change detection cycle. It might lead to performance issues.
Additional property (recommended)
You could introduce additional property to hold the result of the condition in the controller and use it in the template.
Controller (*.ts)
// I assume `campaigns` is initialized in a subscription
ngOnInit() {
someObservable.subscription(
(res: any) => {
this.campaigns = {
...res,
subString: res.description.indexOf('one beam') !== -1
}
},
(error: any) => { }
);
}
Template (*.html)
<div *ngIf="campaigns?.subString; else other">
<!-- contains the sub-string -->
</div>
<ng-template #other>
<!-- does not contain the sub-string -->
</ng-template>

"Cannot read property '0' of undefined" when reading environment variable from mongoDB

I am trying to read a variable which is defined in my javascript. It is a get request from a mongoDB. The whole database is then stored under a variable and is read by the HTML and displayed.
The get request from the MongoDB has an output like this:
(Lets say this is stored under the variable database):
[
{
0:
{
TITLE1: valueone
}
},
{
1:
{
TITLE2: valuetwo
}
}
]
My HTML looks like this:
<p> {{ database?.TITLE1 }} </p>
I get the error Cannot read property '0' of undefined. I understand this is because I need to define [0] to be able to read TITLE1.
Based on this I have tried the following:
<p> {{ database?[0].TITLE1 }} </p>
This has this error: Template parse errors:
Parser Error: Conditional expression database?[0].TITLE1 requires all 3 expressions at the end of the expression [{{ database?[0].TITLE1 }}]
<p> {{ database?.[0].TITLE1 }} </p>
This has this error: Template parse errors:
Parser Error: Unexpected token [, expected identifier or keyword at column 7 in [{{ database?.[0].TITLE1 }}]
<p> {{ database?.0.TITLE1 }} </p>
This has the same error as the one above.
What is the correct way to be able to read the values that I am after. In the HTML the output should be valueone.
Because your database is array, use need use [0] to get first item and your key is number so you need use ['0'] to get property value, you also can use ? to check object null before using TITLE1
Finally you can use {{ database[0]['0']?.TITLE1 }}
Demo https://stackblitz.com/edit/angular-o79rra
Well I mean, at some point you have to think a little about JS basics instead of trying everything until it works ...
From the code you have provided, the syntax would be
{{ data[0]['0'].TITLE1 }}
Try
<p> {{ database[0]['0']?.TITLE1 }} </p>
Do it dynamically by:
<p *ngFor="let item of database; let i = index">
{{item[i]['TITLE' + (i + 1)]}}
</p>

Angular - Cannot concatenate values in HTML page

In our Angular project, we use interpolation as shown below, but we also need to use this interpolated value in the [state] property. But we haev not managed so far. Any idea?
If we set id values as shown below, there is no problem.
<a routerLink="/ticket/details/" [state]="{ id: '5' }" >{{row.TicketId}}</a>
But we cannot get dynamically by obtaining row.TicketId (it is obtained as label in {{row.TicketId}}) but cannot concatenate with id parameter.
<a routerLink="/ticket/details/" [state]="{ id: {{row.TicketId}} }" >{{row.TicketId}}</a>
The brackets in [state]="..." tell Angular to evaluate the template expression, so you cant use interpolation there. So, as I said in comment it should be:
[state]="{ id: row.TicketId }"
Try [state]="{ id: row.TicketId }"

Check and print occurrences of an array of string in a dataset in Python

I want to check if an array of strings occur in a dataset and print those rows where the string array elements occur.
rareTitles = {"Capt", "Col", "Countess", "Don", "Dr", "Jonkheer", "Lady",
"Major", "Mlle", "Mme", "Ms", "Rev", "Sir"}
dataset[rareTitles in (dataset['Title'])]
I am getting following error:
TypeError: unhashable type: 'set'
First of all, I think the comparison should go the other way around - you look for a dataset['Title'], that contains string from rareTitles.
You can use str attribute of a pandas DataSeries, which allows as to use string methods, like contains. As this method accepts also a pattern as a regular expression, you can put as an argument something like 'Capt|Col...'. To join all elements of a set you can use str.join() method.
So the solution would be
dataset[dataset['Title'].str.contains('|'.join(rareTitles))]
Link to documentation: pandas.Series.str.contains

IF condition with <div> in the view file of MVC

I am able to pass data to view file, but need to display them in different format with .
I try to use if statement to check the form name.
It returns error said "Operator '==' cannot be applied to operands of type 'System.Web.HtmlString' and 'string'".
Can I add blocks within IF condition? how to validate data within if condition in view file? Thank you! Here is the code:
#{ foreach (var form in #ViewBag.FormContent)
{
if (Html.Raw(form.Name) == "xyz") //pull up the title and text for the form
{
#Html.Raw(form.FormTitle)
<div class="panel-body">
<div style="height: 300px; overflow: auto; padding:15px;">
#Html.Raw(form.FormText)
</div>
</div>
}
}}
HTML.Raw returns an object that implements IHtmlString. It does not return a string. It doesn't even support ToString. Its only member is ToHtmlString(), which returns a string.
If you want to compare the output of Html.Raw with "xyz", you need to convert it to a string first. So instead of
if (Html.Raw(form.Name) == "xyz")
use something like
if (Html.Raw(form.Name).ToHtmlString() == "xyz")
Or... don't even bother with Html.Raw to begin with. Don't think you need it. Just write this:
if (form.Name == "xyz")