Conditionally Display Element in Angular 7 - html

I have a <select> element in my Angular component that, based on the selected item, returns the identifier of that item.
I want to know how I would be able to conditionally display a <div> when the identifier is either not undefinded or 0.
I have the following code
<div *ngIf="this.id != undefined || this.id != null"></div>
However, it still display's the element even though the condition should theoretically be satisfied as, at the point of the <select> not having a value, should be undefined.
Are there any suggestions that would conditionally display an element using the *ngIf directive based on an id returned from a <select>?

It depends on how the select is set up. For eg., if it's of the following form
<select #sel (change)="change(sel.value)" [(ngModel)]="id">
<option [ngValue]="undefined">Undefined</option>
<option *ngFor="let option of options" [ngValue]="option">{{ option }}</option>
</select>
with options = [ 0, 1, 2, 3, 4, 5 ];
And if id is declared as id: any; in the controller, then explicit checks to undefined and null isn't required. You could do null check just with the following
<div *ngIf="id && id !== 0; else undefinedBlock">
ID is defined: {{ id }}
</div>
<ng-template #undefinedBlock>
ID is undefined
</ng-template>

Use ng-template when you want to show something depending on some condition. See example
Instead of:
<div *ngIf="isDisplayed">Item 1</div>
<div *ngIf="!isDisplayed">Item 2</div>
You can do this:
<div *ngIf="isDisplayed; else showItem2">Item 1</div>
<ng-template #showItem2>
Item 2
</ng-template>

I want to know how I would be able to conditionally display a <div>
when the identifier is either undefinded or 0.
First of all make sure this is not undefined in all cases. then you can use sth like this :
<div *ngIf="this.id"></div>
Look at this fiddle which you can manually set id to null or remove it (e.g undefined)

Related

Data binding <select> element's selected index with Angular

Could I please ask what I am doing wrong in the following:
Firstly, the following works fine:
I have the following variables in my .ts component:
public m_array = ["one", "two", "three", "four"];
public m_selectedValueIndex = "two";
and in my html I have:
<select [(ngModel)]="m_selectedValueIndex">
<option *ngFor = 'let num of m_array'>
{{num}}
</option>
</select>
All works fine, and I can see that I have two-way binding on m_selectedValueIndex.
But If I change to the code below things do not work as I expected they would:
.TS code:
public m_array = ["one", "two", "three", "four"];
public m_selectedValueIndex = 2; // THIS IS NOW A NUMBER
html code:
<select [(ngModel)]="m_array[m_selectedValueIndex]"> // THIS IS NOW AN INDEX TO ARRAY
<option *ngFor = 'let num of m_array'>
{{num}}
</option>
</select>
Initially it looks like it's working because the initially selected item is indeed the one with and index of m_selectedValueIndex. But if I use the list box then the values listed actually change.
I may initially have:
one
two
three
four
(where italics indicates that it is selected). This is as I would expect because m_selectedValueIndex = 2.
But if I click on any item (say "four" for example) then the listbox contents change to:
one
two
four
four
i.e. it is replacing item at index m_selectedValueIndex with my selection. Also the value of m_selectedValueIndex remains 2.
Just wanted to see if I could bind by index instead of value.
Thanks for any help.
You need to bind the option value to the array's index using [value]="ndx", (after defining it using let ndx = index within *ngFor)
like the following:
<select [(ngModel)]="m_selectedValueIndex"> // THIS IS NOW AN INDEX TO ARRAY
<option *ngFor="let num of m_array; let ndx = index" [value]="ndx">
{{ num }}
</option>
</select>

How to use object child as value in select without matching property name

I want to set value of select field to the one specified in repairData property called reportShiftId, but it doesn't work. On the other hand if i make Shift object inside repairData and reference it with reportShift.id it works.
In not working code when i change repairData.reportShiftId which is ng model of select, select option does not change, but after i choose something manually in select, ngModel starts working properly.
Not working code:
export class RepairData {
reportShiftId: number;
...
}
-
<select class="form-control" name="shift" [(ngModel)]="repairData.reportShiftId">
<option *ngFor="let shift of shifts" [ngValue]="shift.id">{{shift.name}}</option>
</select>
Working code:
export class RepairData {
reportShift: Shift;
...
}
-
<select class="form-control" name="shift" [(ngModel)]="repairData.reportShift.id">
<option *ngFor="let shift of shifts" [ngValue]="shift.id">{{shift.name}}</option>
</select>
How to use reportShiftId(number) instead of reportShift.id(Shift.number)?
Try to implement an compareWith function like so :
<select class="form-control" name="shift" [compareWith]="compareWithFunction" [(ngModel)]="repairData.reportShiftId">
<option *ngFor="let shift of shifts" [ngValue]="shift.id">{{shift.name}}</option>
</select>
compareWithFunction(item1,item2){
return item1 && item2 ? item1.id === item2.id : item1 === item2;
}
I know what the problem was.
After i changed name html attribute from shift to reportShift (the same name as object property) it started working.
Actually i think i had more than one select with the same name so that could be the problem.

Add an attribute on a condition with angular 2

I have a simple dropdown that is populated from an array.
Users will be editing a record in a form where the priority of the record can be selected from the mentioned dropdown. I'm having difficulty with setting the selected item in that dropdown.
Here's my code for that dropdown:
<select *ngIf="formModel" [(ngModel)]="record.priority" formControlName="priority">
<option value="-1">Select priority</option>
<option *ngFor="let priority of formModel.priorities"
[ngValue]="priority"
[innerHtml]="priority.name"
[selected]="priority.id == record.priority.id"></option>
</select>
The selected priority of the record is however not selected, the resulting HTML shows selected="true".
When I change the code to the following:
[selected]="(priority.id == record.priority.id ? '' : null)"
The result is selected="", but the option is stil NOT selected.
I have already confirmed that that particular option should be selected.
Also when I change the HTML in Firebug to just selected the option is selected.
So my question is: how can I add an attribute on a certain condition so that the attribute is not added to other elements with an empty value?
Using two-way-binding is discouraged in reactive forms. The point is to utilize the form controls instead. Why use reactive form, if you are using two-way-binding? That would mean the model driven form is totally redundant. So if you want to solve this problem using the model-driven form, I'd suggest the following:
Since you are using a separate object (record.priority) it cannot automatically be bound as the pre-selected value, you'd have to somehow create a reference. So when building a form you can do this:
this.myForm = this.fb.group({
priority: [this.formModel.priorities.find(x => x.id == this.record.priority.id)]
});
And the template would look like this:
<form [formGroup]="myForm">
<select *ngIf="formModel" formControlName="priority">
<option value="-1">Select priority</option>
<option *ngFor="let priority of formModel.priorities"
[ngValue]="priority"
[innerHtml]="priority.name"></option>
</select>
</form>
Now the value object you are getting from the form holds this value.
if having the record coming async, you can set a boolean flag to not show the form until the values have been set. Or you can build an empty form initially and then use setValue() for the form control.
DEMO
EDIT: Looking closer, that you want to have the condition to set null if there is no value for record.priority? That can be done well in the form control as well:
priority: [this.record.priority ? this.formModel.priorities.find(x => x.id == this.record.priority.id) : null]
Try this :
<select *ngIf="formModel" [(ngModel)]="record.priority.id" formControlName="priority">
<option value="-1">Select priority</option>
<option *ngFor="let priority of formModel.priorities"
[ngValue]="priority.id"
[innerHtml]="priority.name"></option>
</select>
[ngValue]="priority.id" and [(ngModel)]="record.priority.id" should point to the same value , and it will work automatically ,
There is no need to write [selected]="priority.id == record.priority.id"

Show element if observable value is null

Is it possible to use the Knockout's visible: or if: data bindings to check to see if an observable's value is (explicitly) null?
I've got two radio buttons, and if either one is checked, it sets an observable's value to either "True" or "False". Otherwise the observable's value is null. I'd like an element to conditionally display if the observable value is null. The following doesn't seem to work:
<div data-bind="visible: specificObservable === null"> Example </div>
<!-- shows the element when null, but not false, nor 'False' -->
Guessing that specificObservable is an observable, try:
<div data-bind="visible: specificObservable() === null"> Example </div>
You need to call the observable to get the actual value it contains. specificObservable is a function and therefore not null, even if the value it contains is null.
This is something that can trip you up in knockout because knockout will automatically unwrap observables if they are used by themselves. So if you did:
<div data-bind="visible: specificObservable"> Example </div>
And it will call specificObservable for you and be visible if specificObservable() is truthy. But once you start using it in a longer statement you need to explicitly unwrap it yourself.
Don't forget the closing double quote " after the call to function specificObservable()

AngularJS ngClass conditional

Is there any way to make an expression for something like ng-class to be a conditional?
For example, I have tried the following:
<span ng-class="{test: 'obj.value1 == \'someothervalue\''}">test</span>
The issue with this code is that no matter what obj.value1 is, the class test is always applied to the element. Doing this:
<span ng-class="{test: obj.value2}">test</span>
As long as obj.value2 does not equal a truthy value, the class in not applied. Now I can work around the issue in the first example by doing this:
<span ng-class="{test: checkValue1()}">test</span>
Where the checkValue1 function looks like this:
$scope.checkValue1 = function() {
return $scope.obj.value === 'somevalue';
}
I am just wondering if this is how ng-class is supposed to work. I am also building a custom directive where I would like to do something similar to this. However, I can't find a way to watch an expression (and maybe that is impossible and the reason why it works like this).
Here is a plnkr to show what I mean.
Your first attempt was almost right, It should work without the quotes.
{test: obj.value1 == 'someothervalue'}
Here is a plnkr.
The ngClass directive will work with any expression that evaluates truthy or falsey, a bit similar to Javascript expressions but with some differences, you can read about here.
If your conditional is too complex, then you can use a function that returns truthy or falsey, as you did in your third attempt.
Just to complement: You can also use logical operators to form logical expressions like
ng-class="{'test': obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}"
Using ng-class inside ng-repeat
<table>
<tbody>
<tr ng-repeat="task in todos"
ng-class="{'warning': task.status == 'Hold' , 'success': task.status == 'Completed',
'active': task.status == 'Started', 'danger': task.status == 'Pending' } ">
<td>{{$index + 1}}</td>
<td>{{task.name}}</td>
<td>{{task.date|date:'yyyy-MM-dd'}}</td>
<td>{{task.status}}</td>
</tr>
</tbody>
</table>
For each status in task.status a different class is used for the row.
Angular JS provide this functionality in ng-class Directive. In which you can put condition and also assign conditional class. You can achieve this in two different ways.
Type 1
<div ng-class="{0:'one', 1:'two',2:'three'}[status]"></div>
In this code class will be apply according to value of status value
if status value is 0 then apply class one
if status value is 1 then apply class two
if status value is 2 then apply class three
Type 2
<div ng-class="{1:'test_yes', 0:'test_no'}[status]"></div>
In which class will be apply by value of status
if status value is 1 or true then it will add class test_yes
if status value is 0 or false then it will add class test_no
I see great examples above but they all start with curly brackets (json map). Another option is to return a result based on computation. The result can also be a list of css class names (not just map). Example:
ng-class="(status=='active') ? 'enabled' : 'disabled'"
or
ng-class="(status=='active') ? ['enabled'] : ['disabled', 'alik']"
Explanation: If the status is active, the class enabled will be used. Otherwise, the class disabled will be used.
The list [] is used for using multiple classes (not just one).
There is a simple method which you could use with html class attribute and shorthand if/else. No need to make it so complex. Just use following method.
<div class="{{expression == true ? 'class_if_expression_true' : 'class_if_expression_false' }}">Your Content</div>
I am going to show you two methods by which you can dynamically apply ng-class
Step-1
By using ternary operator
<div ng-class="condition?'class1':'class2'"></div>
Output
If your condition is true then class1 will be applied to your element else class2 will be applied.
Disadvantage
When you will try to change the conditional value at run time the class somehow will not changed. So I will suggest you to go for step2 if you have requirement like dynamic class change.
Step-2
<div ng-class="{value1:'class1', value2:'class2'}[condition]"></div>
Output
if your condition matches with value1 then class1 will be applied to your element, if matches with value2 then class2 will be applied and so on. And dynamic class change will work fine with it.
Hope this will help you.
Angular syntax is to use the : operator to perform the equivalent of an if modifier
<div ng-class="{ 'clearfix' : (row % 2) == 0 }">
Add clearfix class to even rows. Nonetheless, expression could be anything we can have in normal if condition and it should evaluate to either true or false.
Using function with ng-class is a good option when someone has to run complex logic to decide the appropriate CSS class.
http://jsfiddle.net/ms403Ly8/2/
HTML:
<div ng-app>
<div ng-controller="testCtrl">
<div ng-class="getCSSClass()">Testing ng-class using function</div>
</div>
</div>
CSS:
.testclass { Background: lightBlue}
JavaScript:
function testCtrl($scope) {
$scope.getCSSClass = function() {
return "testclass ";
}
}
For Angular 2, use this
<div [ngClass]="{'active': dashboardComponent.selected_menu == 'mapview'}">Content</div>
use this
<div ng-class="{states}[condition]"></div>
for example if the condition is [2 == 2], states are {true: '...', false: '...'}
<div ng-class="{true: 'ClassA', false: 'ClassB'}[condition]"></div>
ng-class is a Directive of core AngularJs. In which you can use "String Syntax", "Array Syntax", "Evaluated Expression", " Ternary Operator" and many more options described below:
ngClass Using String Syntax
This is the simplest way to use ngClass. You can just add an Angular variable to
ng-class and that is the class that will be used for that element.
<!-- whatever is typed into this input will be used as the class for the div below -->
<input type="text" ng-model="textType">
<!-- the class will be whatever is typed into the input box above -->
<div ng-class="textType">Look! I'm Words!
Demo Example of ngClass Using String Syntax
ngClass Using Array Syntax
This is similar to the string syntax method except you are able to apply multiple classes.
<!-- both input boxes below will be classes for the div -->
<input type="text" ng-model="styleOne">
<input type="text" ng-model="styleTwo">
<!-- this div will take on both classes from above -->
<div ng-class="[styleOne, styleTwo]">Look! I'm Words!
ngClass Using Evaluated Expression
A more advanced method of using ngClass (and one that you will probably use the most) is to evaluate an expression. The way this works is that if a variable or expression evaluates to true, you can apply a certain class. If not, then the class won't be applied.
<!-- input box to toggle a variable to true or false -->
<input type="checkbox" ng-model="awesome"> Are You Awesome?
<input type="checkbox" ng-model="giant"> Are You a Giant?
<!-- add the class 'text-success' if the variable 'awesome' is true -->
<div ng-class="{ 'text-success': awesome, 'text-large': giant }">
Example of ngClass Using Evaluated Expression
ngClass Using Value
This is similar to the evaluated expression method except you just able to compares multiple values with the only variable.
<div ng-class="{value1:'class1', value2:'class2'}[condition]"></div>
ngClass Using the Ternary Operator
The ternary operator allows us to use shorthand to specify two different classes, one if an expression is true and one for false. Here is the basic syntax for the ternary operator:
ng-class="$variableToEvaluate ? 'class-if-true' : 'class-if-false'">
Evaluating First, Last or Specific Number
If you are using the ngRepeat directive and you want to apply classes to the first, last, or a specific number in the list, you can use special properties of ngRepeat. These include $first, $last, $even, $odd, and a few others. Here's an example of how to use these.
<!-- add a class to the first item -->
<ul>
<li ng-class="{ 'text-success': $first }" ng-repeat="item in items">{{ item.name }}</li>
</ul>
<!-- add a class to the last item -->
<ul>
<li ng-class="{ 'text-danger': $last }" ng-repeat="item in items">{{ item.name }}</li>
</ul>
<!-- add a class to the even items and a different class to the odd items -->
<ul>
<li ng-class="{ 'text-info': $even, 'text-danger': $odd }" ng-repeat="item in items">{{ item.name }}</li>
</ul>