Angular - Display different dropdown values based on condition - html

I am displaying data value as dropdown if below condition in html is met.
I would like to add another condition where on change of another dropdown which contains companies name I show data1value. For example if 1st dropdown (companies name) is changed toAmazonthen I only displaydata1` as its value
<dd>
<mat-select *ngIf="editMode"; else showData" [disabled]="!editMode"
[(ngModel)]="term.data" (ngModelChange)="recordModified.emit()">
<mat-option *ngFor="let tag of data" [value]="tag.value">{{tag.text}}</mat-option>
</mat-select>
<ng-template #showData>{{term.data}}</ng-template>
</dd>
data = [
{value: '1', text: 'Amazon'},
{value: '2', text: 'Google'},
{value: '3', text: 'Apple'},
data1 = [
{value: '1', text: 'Amazon'},

From what I can gather you want to access the data that has been selected by the dropdown, correct? You're close... check out this demo for a working version https://stackblitz.com/edit/angular-ivy-xmxqpg?file=src%2Fapp%2Fapp.component.ts

Related

I have created a dropdown in Angular where there are values from 1 to 20 in it. If I select number <10 , it will show a msg and if >10 then diff. msg

html: -
<div class="form-group">
<label for="experience" class="form-label">I am experience</label>
<select class="custom-select" formControlName="experience" name="experience" onchange="change(this);">
<option *ngFor="let experience of experiences">{{experience}}</option>
</select>
</div>
ts:-
experiencesLessThanTenYears = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
experiencesMoreThanTenYears = ['10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20'];
experiences = [ ...this.experiencesLessThanTenYears, ...this.experiencesMoreThanTenYears];
ngOnInit(): void {
this.registrationForm = this.fb.group({
firstName: ['', [Validators.required, Validators.minLength(3)]],
lastName: ['', [Validators.required, Validators.minLength(3)]],
startDate: [ '',[Validators.required]],
endDate: ['',[Validators.required]],
experience: ['',[Validators.required,]],
})
I want to show message on selecting values less than 10 and greater than 10 on my view. Please help me on how to do that.
I tried using the change event of my html select but it was not working. I was hoping to make a custom validator but I don't know was just an idea. Please someone help me out
{{+registrationForm.get('experience').value>10?
'You have a great experience':
'You have a poor experience'}}.
But this makes that if you don't selected anything show that you have a poor experience.
We can use a ng-container *ngIf in the way
<ng-container *ngIf="registrationForm.get('experience').value">
{{+registrationForm.get('experience').value>10?
'You have a great experience':
'You have a poor experience'}}.
</ng-container>
Well, as we use a *ngIf, we can create a temporaly variable
<ng-container *ngIf="registrationForm.get('experience').value as experience">
{{+experience>10?
'You have a great experience':
'You have a poor experience'}}.
</ng-container>
The another way is use a ternary operator inside a ternary operator. Really is an ugly (but equal effective solution)
{{registrationForm.get('experience').value?
+registrationForm.get('experience').value>10?
'You have a great experience':
'You have a poor experience':
''}}

How to preselect PrimeNG Checkbox items?

I am not able to get already selected item. In this code in rp which is an array of type Permission which has one element in it , So basically that value should be selected when I load this div. What will be the mistake?
This is My HTML:-
<div class="gapRowSmall displayFlex flexColumn mb-small" *ngIf="(permissions$ | async)! as permissions">
<div *ngFor="let permission of permissions" class="p-field-checkbox">
<p-checkbox [value]="permission" [(ngModel)]="rp" class=" mr-small"></p-checkbox>
<label>{{permission.name}}</label>
</div>
<div class="displayFlex flexJustifyEnd">
<p-button type="submit" label="Save" styleClass="primary" (onClick)="savePermissions()"
[appSubmitIndicator]="(isSubmitInProgress$ | async)!"></p-button>
</div>
</div>
This is My ts file:-
permissions$ = this.store.select(permissionSelector)
.pipe(takeUntil(this.permissionManagementSubject));
rp: Permission[] = [{ name: 'Create New Transitions', id: 'a45d7806-fbf8-4df7-8248-6f636288ff23' },];
The item in your rp array must completely match one of the items in your Observable permissions array. If not all the fields in the object match, then it will not be selected.
So if the permissions would be loaded in the constructor like this:
constructor() {
this.permissions$ = of([
{name: "aaaaa", id: '123456-789012'},
{name: "bbbbb", id: '223456-789012'},
{name: "ccccc", id: '323456-789012'}
])
}
and the selected permissions in rp would be :
rp: Permission[] = [
{ name: 'aaaaa', id: '123456-789012' },
{ name: 'bbbbb', id: '223456-' }, // This one is incomplete, thus no match
];
Then the second one, will not be selected although partially it is matching.
I've a working example of this in stackblitz. https://stackblitz.com/edit/primeng-checkbox-demo-9rhzru?file=src/app/app.component.ts

ng select - multiple values - select same values more than once

is there a way to use ng select to have multiple selections and the possibility to have the same value/s more than once in the same selection?
I could only achieve multiple with each value possible to choose only once:
HTML code:
<ng-select [closeOnSelect]="false" [selectableGroup]="true" [items]="allowedValues"
[(ngModel)]="selectedValuesArray" [selectableGroupAsModel]="false"
(change)="raiseChangeEvent($event)" name="dropdown-element" [multiple]="true" [maxSelectedItems]="maxLength"
[clearable]="false">
<ng-template ng-option-tmp let-item="item">
<div class="option-line">
<p>{{item == null ? 'N/A' : item}}</p>
</div>
</ng-template>
</ng-select>
You could exploit the bindLabel and bindValue attributes.
suppose you pass in the following items:
allowedValues= [
{label: 1, value: 'first_0'},
{label: 2, value: 'second_0'}
]
Your HTML will look like this, mind the addition of bindLabel and bindValue, the change in (change) and the [hideSelected] attribute:
<ng-select [closeOnSelect]="false" [selectableGroup]="true" [items]="allowedValues"
[(ngModel)]="selectedValuesArray" [selectableGroupAsModel]="false"
(change)="raiseChangeEvent($event); addItem($event)" name="dropdown-element" [multiple]="true" [maxSelectedItems]="maxLength"
[clearable]="false" bindLabel="label" bindValue="value" [hideSelected]="true">
<ng-template ng-option-tmp let-item="item">
<div class="option-line">
<p>{{item == null ? 'N/A' : item}}</p>
</div>
</ng-template>
</ng-select>
Whenever an item is selected you could insert a new one in the list with the addItem() function. For example when the user selects 1, add {label: 1, value: 'first_1'} to the allowedValues. This way you will end up with an array of values that are unique, but the user is tricked into believing he is actually clicking the same items over and over again.

Display label displayed in options as the title of select

How to show option.Brand.Name as the title of the select field without using java script and changing the ng-model?
<select ng-model="detail.BrandId" title="" class="form-control" disabled>
<option ng-repeat="option in mainCtrl.products" ng-selected="option.Id === detail.ProductId" ng-value="option.BrandId">{{option.Brand.Name}}</option>
</select>
AngularJS and select-options
Try using ng-options AngularJS ngOptions directive within select element itself. Then you don't need to add each option element yourself using ng-repeat.
Clarification
The title-attribute belongs to the select-element and will show if you hover over the select. You would like the title to reveal the current selected option? Did I understand you correctly?
How to show option.Brand.Name as the title of the select field
Curious, where this detail.ProductId comes from? Is the brand preselected by product-id (see your code)?
ng-selected="option.Id === detail.ProductId"
Solution space
Your requirements/restrictions are:
without using JavaScript (maybe because you can't change the sources)
without changing the ng-model (because you need there only the BrandId for some database-reasons)
So since the title of the select-element has no access to the options inside, the only way to set it is depending on the current selection, i.e. your detail.BrandId. So the title can only set dynamically (depending on the current selection) by using standard-angularJS means, as:
{{ expression }} expressions
{{ expression | filter }} array-filter
Expected behavior
The only scope-variable changed by selecting is specified within select's ng-model as detail.BrandId. This will be set when user selects an option to its property BrandId. When user selects between options they will be visible with ther BrandName as label. After selection this BrandName (label of the option) should be shown as title of the entire select element.
So we need to get from detail.BrandId (selected ng-model) to related options BrandName (as this should show as title).
Possible Solution
Only way is to use standard angular expressions/filters/array-indexing to get the whole option by the selected detail.BrandId (ng-model)
Then we can lookup the option.BrandName by this equation after selected detail.BrandId === option.BrandId
var app = angular.module('app', []);
app.controller('mainCtrl', function($scope){
$scope.products = [
{Id: 0, name: 'Watson', brandId: 1, brandName:"IBM"},
{Id: 1, name: 'DB2', brandId: 1, brandName:"IBM"},
{Id: 2, name: 'Windows', brandId: 2, brandName: "Microsoft"},
{Id: 3, name: 'Office', brandId: 2, brandName: "Microsoft"}
];
$scope.detail = { ProductId: 3, BrandId: null };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<!DOCTYPE html>
<html>
<body data-ng-app="app" data-ng-controller="mainCtrl">
<table border="1">
<tr>
<th>Product Id</th><th>Product Name</th><th>Choose Brand</th><th>Brand Id</th>
</tr>
<tr>
<td>{{detail.ProductId}}</td>
<td>{{ (products | filter: {Id: detail.ProductId})[0].name }}</td>
<td>
<select class="form-control"
ng-model="detail.BrandId"
ng-init="detail.BrandId = (products | filter: {Id: detail.ProductId})[0].brandId"
ng-options="o.brandId as ('['+ o.Id +'] '+ o.name +' : '+ o.brandName +' ('+ o.brandId +')') for o in products"
title="{{ (products | filter: {brandId: detail.BrandId})[0].brandName}}"
>
<!-- default option when not preset by detail.ProductId-->
<option value="">-- please choose brand --</option>
</select>
</td>
<td>{{detail.BrandId}}</td>
</tr>
</table>
<hr/>
<p>Product is predefined. So the brand is pre-selected by product. BUT: after brand is selected, the product-details do NOT change!</p>
Selected <strong>detail</strong>:
<pre ng-model="selected">{{detail | json}}</pre>
</body>
</html>
See also
For using ng-options, see also plunkr example.
You can register the selected option object in the ng-repeat parent scope by using as alias-expression provided by ng-repeat.
In your case you just need to do something like that:
<select ng-model="detail.BrandId"
title="{{options | selectedProductFilter : detail.ProductId}}"
class="form-control"
disabled>
<option ng-repeat="option in mainCtrl.products as options"
ng-selected="option.Id === detail.ProductId"
ng-value="option.BrandId">
{{option.Brand.Name}}
</option>
</select>
The options object will be available in your controller closure and you can display the title by using a custom filter.
angular.module("app").filter('selectedProductFilter',
function () {
return function (input, id) {
if (!input) return "";
let occurence = input.filter(function (x) {
return x.Id == id;
});
return occurence.length > 0 ? occurence[0].Brand.Name: "";
}
}
);
you need to do ng-change event in your select and call function in it that change the value of label text to the select value name. something like below
In Html
ng-change="changedValue(detail.BrandId)"
In JS
$scope.changedValue = function(item) {
//change label name here
}
fill ng-model by "option" not "option.BrandId"
then you can set title like this :
mainCtrl.products['ng-model-name'].Brand.Name
Here's how you could achive this:
(function () {
"use strict";
const app = angular.module("app", []);
app.controller("app.AppCtrl", $scope => {
$scope.selectedOption = null;
$scope.optionList = [{_id: 1, label: 'Option 1'}, {_id: 2, label: 'Option 2'}];
});
})();
body {
margin: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="app.AppCtrl">
<select title="{{selectedOption.label}}" class="form-control" ng-model="selectedOption">
<option ng-repeat="option in optionList" ng-value="option"> {{option.label}}</option>
</select>
</div>
Try using ng-init,
add ng-init to your select tag and put your object index value you want to be selected by default.
e.g.
Your code
<select ng-model="detail.BrandId" title="" class="form-control" disabled>
<option ng-repeat="option in mainCtrl.products" ng-selected="option.Id === detail.ProductId" ng-value="option.BrandId">{{option.Brand.Name}}</option>
</select>
adding following code (Suppose I want index 0 by index):
ng-init="detail.BrandId = option[0].Brand.Name"
It will look like this :
<select ng-model="detail.BrandId" ng-init="detail.BrandId = option[0].Brand.Name" title="" class="form-control" disabled>
<option ng-repeat="option in mainCtrl.products" ng-selected="option.Id === detail.ProductId" ng-value="option.BrandId">{{option.Brand.Name}}</option>
</select>
or Check these thread's
how to use ng-option to set default value of select element
How to set default value in ng-options

How to handle checkbox using json object in angularjs 4

I had displayed below data in checkbox,
roomLists = {'4': {'name': 'Standard Room', 'typeID': '4', 'price': 100}, '5': {'name': 'Delux Room', 'typeID': '5', 'price': 100}}
this json object is retrieve using http. For testing purpose i have store it in roomlist.
Using pipe, data are getting display properly inside modal
<app-modal #modal1>
<div class="app-modal-body">
<div *ngFor="let room of roomLists | jsonPipe">
<label>
<input type="checkbox"/>{{room.name}}
</label>
</div>
</div>
but when I try to click on check box its not getting click. Is something i m missing in code.
Guess you are pairing checkbox with its own label, you can try give checkbox an id and and give label a for property which bind to the id of checkbox.
<div *ngFor="let room of roomLists | jsonPipe; let i = index;">
<label for="{{'checkbox' + i}}">
<input id="{{'checkbox' + i}}" type="checkbox"/>{{room.name}}
</label>
</div>