Conditionally add string to HTML with Angular expression - javascript

I have the following :
<div>{{animalType}}</div>
which evaluates to dog.
Can I conditionally add an sif animalTypeevaluates to anything other than dog?
Something like this : which doesn't work
<div>{{animalType}} {{'s' : !animalType == 'dog'}}</div>
So I would getcats

Use ternary operator in expression as follow:
<div>{{animalType}}{{animalType != 'dog' ? 's' : '' }}</div>

Alternatively
<div>{{animalType}}<span ng-show="animalType!='dog'">s</span></div>

Not tested, but try this simple snippet:
<div>{{animalType === "dog" ? animalType : "s"}}</div>
By the way, if you want to switch only between two values, from my point of view, logically appealing would be something like that:
<div>{{isDog ? "dog" : "s"}}</div>
$scope.isDog = true/false

You could also use ng-if
<div>{{animalType}}<div ng-if="animalType !== 'dog'">s</div></div>

Related

Angular - Ternary operator with a ternary operator response

I have a ternary operator in my angular HTML. I'm having difficulty with the formatting. If the value equals the files length, it should return Good, if it doesn't I need to check some custom values. I check to see if the custom value exists (customs?.album_title) and then determine what to show. If both options were strings, it works completely fine. However, I need My Text to prepend the customs.album_title value and I'm not entirely sure how to do that. As you can see in the example below (which is naturally incorrect), the result would be customs?.album_title as a string, opposed to My Text + whatever the customs.album_title value is.
Any help would be greatly appreciated.
{{ value == files.length ? 'Good' : customs?.album_title ? 'My Text customs.album_title' : 'String Two' }}
Maybe you mean like this (using ${var})
{{ value == files.length ? 'Good' : customs?.album_title ? `My Text ${customs.album_title}` : 'String Two' }}
I'm not sure but I think Template Literals are not yet supported by Angular on HTML templates.
So for now, you can try to solve it by string concatenation
{{ value == files.length ? 'Good' : customs?.album_title ? ('My Text ' + customs.album_title) : 'String Two' }}
You can try this:
{{ value == files.length ? 'Good' : (customs?.album_title ? (('My Text ') + customs.album_title) : 'String Two') }}

Replace affects all strings in an array

I am having some issues about replacing. I am fetching some integers from DB. And if the number fetched is just 1 then I replace it with "empty", but when I do that, it affects all numbers that have 1 in them.
Here is what I am doing, first calling toString and then replace
<tr v-if="moreIndex < one.length"  v-for="moreIndex in morePro">
<td>{{one[moreIndex].products}}</td>
<td>{{priceSep(one[moreIndex].price).toString().replace("1", "empty")}}</td>
</tr>
So I am changing "1" to empty but if any other data has includes 1 then output look like this...
5empty98
How can I fix this problem?
You can check the length with Conditional (ternary) operator
.:
<td>{{priceSep(one[moreIndex].price).toString().length == 1 ? priceSep(one[moreIndex].price).toString().replace("1", "empty") : priceSep(one[moreIndex].price).toString()}}</td>
May be, you can try directly set the value if the value is 1:
<td>{{priceSep(one[moreIndex].price).toString() == "1" ? "empty" : priceSep(one[moreIndex].price).toString()}}</td>
You can check the length of the string before replacing it
{{priceSep(one[moreIndex].price).toString().length > ?
priceSep(one[moreIndex].price).toString() :
priceSep(one[moreIndex].price).toString().replace("1", "empty")
}}
You can use RegExp:
{{priceSep(one[moreIndex].price).toString().replace(/^1$/, "empty")}}

Simplify simple ternary expression

I want to validate undefined attributes from an object so I use ternary like this
item.subitem ? item.subitem.toString() : ''
Is there any way to simplify this expression using || or && ?
It's simple:
item.subitem && item.subitem.toString() || ''
Or simply like:
(item.subitem || '').toString()
OR,
''+(item.subitem || '')
If you can use optional chaining, then it can be even more simple:
item.subitem?.toString()
See this post for more detail.
As #Thomas mentioned in comment, you can also use an array and convert to a string:
[item.subitem].toString();
This should clear how it will work:
[].toString(); // ''
[undefined].toString(); // ''
['foo'].toString(); // 'foo'
['foo', 'bar'].toString(); 'foo,bar'
Yes you can
(item.subitem || '').toString()

If value is 0 then return empty string in Angularjs

Is it possible to return empty string when some value is "0", but from HTML page using angularJs?
If I have something like this:
<p>External | Year of Birth: {{profileCtrl.person.year}}</p>
Can I write some expression right there that will check the value for profileCtrl.person.year? If the value is "0" then return empty string, else return value of profileCtrl.person.year.
Something like this is very easy to do in languages like C#, but since I am very new to Angular I was unable to find out if this technology has a power to do such thing?
Can someone help me out with this maybe?
You can do it like this:
{{profileCtrl.person.year === 0 ? "" : profileCtrl.person.year}}
You can use a ternary operator to achieve this;
{{profileCtrl.person.year === 0 ? "" : profileCtrl.person.year}}
This basically says, if it's 0 provide "", else provide the year.
Hope it helps!
You could use the ternary operator ?:
{{ profileCtrl.person.year === 0 ? "" : profileCtrl.person.year }}
You could use a logical OR ||, which uses the second value if the first value is falsy.
<p>External | Year of Birth: {{profileCtrl.person.year || ""}}</p>
Another solution could be to show the wole part, with ng-show attribute and a truthy value. On a falsy value the part is hidden.
<p ng-show="profileCtrl.person.year">External | Year of Birth: {{profileCtrl.person.year}}</p>
Use ternary operator:
<p>External | Year of Birth: {{profileCtrl.person.year !== 0 ? profileCtrl.person.year : ""}}</p>
Another approach might be (haven't checked):
<p>External | Year of Birth: {{profileCtrl.person.year || ""}}</p>
you can use filter in your code for return empty
//js file
app.filter("filterName",function(){
return function(input){
switch(input){
case 0:
return "";
}
});
<!-- html page -->
{{input | filterName}}

Conditional logic jsx react

I am trying to apply more than 1 condition to className in my jsx view. However it won't let me.
It only listens to the first condition.
className={usernameFocus ? "toggled" : "" || usernameValidated ? "validated" : ""}
I have tried several combinations:
className={usernameFocus ? "toggled" : "" + usernameValidated ? "validated" : ""}
How could I accomplish more than one conditional to add classNames to my element?
Your order of operations is mixed up. Put your separate conditions in parentheses. Also, you can short-circuit the class evaluation like this:
className={(usernameFocus && "toggled") + " " + (usernameValidated && "validated")}
If you feel extra fancy, you can also use a template string:
className={`${usernameFocus && "toggled"} ${usernameValidated && "validated"}`}
If you do this a lot (multiple booleans), have a look at the officially recommended classnames module by Jed Watson. Link.
With it, you can do it like this:
var usernameClasses = classNames({
'validated': usernameValidated,
'toggled': usernameFocus
});
className={usernameClasses};
I think you are missing a space between the class names for when both are applied, also brackets help with multiple nested conditional statements.
Try this:
className={(usernameFocus ? "toggled" : "") + " " + (usernameValidated ? "validated" : "")}

Categories

Resources