I have an *ngFor which gives me the certain item list of goods and I click a particular button to choose them. As I click my choose button, it temporarily disables the button till the time I get response from my back-end. As I get my response from back-end, the button becomes active to un-choose the item.
The issue I am facing here is, as I click the choose button, it makes all buttons of the list temporarily disabled. But what I want is to make only the clicked button disabled.
My HTML code snippet:
<ion-card *ngFor="let list of list_Array;>
<ion-card-content >
<p style="color: #666; " [innerHTML]="list.item"></p>
</ion-card-content>
<button ion-button color="secondary" clear (click)="activeButton(list._id)" *ngIf="list.isAlreadyChosen==true" [disabled]="ChooseButton">
<div class="chosen"
ng-class="{'chosen': isChosen}">
<p >choose</p>
</div>
</button>
<button ion-button color="secondary" clear (click)="activeButton(list._id)" *ngIf="list.isAlreadyChosen==false" [disabled]="ChooseButton" >
<div class="choosen"
ng-class="{'chosen': isChosen}">
<p >choose</p>
</div>
</button>
</ion-card>
Currently you have ChooseButton flag global, that's why as soon as you change that flag, it reflects everywhere in component context.
Make the ChooseButton property local to each collection element i.e. list.ChooseButton.
[disabled]="list.ChooseButton"
For applying the above you should change the activeButton function to below, before that pass list object on click of button like (click)="activeButton(list)"
Function
activeButton (item) {
item.ChooseButton = true;
console.log("listId", item._id);
}
Answer 1:
As #Pankaj Parkar's answer said - Each item in your list_Array needs to have it's own flag chooseButton, than having 1 common flag for all items to make only the clicked button disabled.
Now, say you have loaded your list_Array. You can use following for loop to add this property to it and set it to false initially:
for(var i = 0; i < list_Array.length; i++){
list_Array[i]['chooseButton'] = false;
}
Now, pass the list as parameter from your UI code to activeButton(list) method like : (click)="activeButton(list)" (Remember to pass an entire object here than list._id as you have done).
Now, in your method:
activeButton(list) {
list.chooseButton = !list.chooseButton;
}
Here, I have negated list.chooseButton to it's previous value (true -> false or false -> true). Hope this helps.
Answer 2:
You already have list.isAlreadyChosen present in your list_Array.
Just do [disabled]="!list.isAlreadyChosen" in first button and [disabled]="list.isAlreadyChosen" in second should solve your problem. Easy. ;)
Here is another way to achieve this:
//component
disableMe:boolean[];
disableThis(id){
this.disableMe[id] = !this.disableMe[id];
}
//template
<button ion-button color="secondary" clear (click)="activeButton(list._id); disableThis(list._id)" *ngIf="list.isAlreadyChosen==true" [disabled]="disableMe[list._id]">
<div class="chosen"
ng-class="{'chosen': isChosen}">
<p >choose</p>
</div>
</button>
Related
I'm using Prime NG Multiselect component and I want to show selectedItemsLabel="{0} Selected" when there are more than 3 selected checkboxes, but if all of the checkboxes are selected, then selectedItemsLabel="All" should be shown in the placeholder.
I'm new to angular and I been following documentation of this MultiSelect component, yet this doesn't show the options to able to implement multiple conditions of properties, and I was wondering if it's even possible.
Example of how It might be
<ng-template pTemplate="filter" let-value let-filter="filterCallback">
<p-multiSelect
[ngModel]="value"
[options]="routeOptions"
placeholder="Any"
(onChange)="filter($event.value)"
optionLabel="name"
selectedItemsLabel="{0} selected"
[maxSelectedLabels]="3"
>
<ng-template let-option pTemplate="item">
<div>
<span class="p-ml-1">{{ option.name }}</span>
</div>
<div *ngIf="[maxSelectedLabels="routeOptions.length - 1"] Then selectedItemsLabel="All"></div>
</ng-template>
</p-multiSelect>
</ng-template>
Yes, you can. First give the component a ref with # like this:
<p-multiSelect
#myMultiSelect
[ngModel]="value"
[options]="routeOptions"
placeholder="Any"
(onChange)="filter($event.value)"
optionLabel="name"
selectedItemsLabel="{0} selected"
[maxSelectedLabels]="3"
>
.......
Then you have access to it:
<div *ngIf="myMultiSelect.maxSelectedLabels === routeOptions.length - 1">Im visible</div>
If the option of maxSelectedLables is the length - 1 of routeOptions then the div is visible. That is how ngIf works
BUT
Thats not what you want. You wanna set the selectedItemsLabel property. And you have it not understand correctly. You set the maxSelectedLables to 3 as example AND set the selectedItemsLabel directly, too! The text of the selectedItemsLabel will be only shown if needed (controlled by the component).
<h5>Basic</h5>
<p-multiSelect #meins [options]="cities" [(ngModel)]="selectedCities" defaultLabel="Select a City" optionLabel="name"
[maxSelectedLabels]="3" selectedItemsLabel="{0} items selected">
</p-multiSelect>
Look here the Stackblitz!
The documentation of ng-prime will helps, too and say:
selectedItemsLabel: Label to display after exceeding max selected labels e.g. ({0} items selected), defaults "ellipsis" keyword to indicate a text-overflow.
UPDATE 18.02.2023
You wanna show "ALL" only if all items selected. So add the onChange event and bind the selectedItemsLabel. Why binding? It has some problems with a condition in it. So we make it inside the code.
HTML
<p-multiSelect [options]="cities" [(ngModel)]="selectedCities" defaultLabel="Select a City" optionLabel="name"
[maxSelectedLabels]="2" [selectedItemsLabel]="bindTest" (onChange)="onChange()">
</p-multiSelect>
Inside the code do the follow with onChange:
Code
onChange() {
if (this.selectedCities.length === this.cities.length) {
this.bindTest = "ALL";
this.changeRef.detectChanges();
}
else {
this.bindTest = "{0} items selected";
this.changeRef.detectChanges();
}
}
Now it works how you wish. One important thing: We use changeRef.detectChanges(); Without this the components selected text will not changing directly. Import it in the components constructor:
constructor(
private countryService: CountryService,
private primengConfig: PrimeNGConfig,
private changeRef: ChangeDetectorRef
) {
.....
I made a Stackblitz of the problem: https://stackblitz.com/edit/primeng-tablefilter-demo-ipt7y1?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts
(Expand the page to the left to view the column filter in the stackblitz)
If you notice, the clear button doesn't clear the selected textbox anymore. After some testing it seems the [(ngModel)] breaks it, I think it got to do something with two-way binding? It is not shown in the stackblitz, but if you include
(onChange)="filter($event.value)"
the clear button still clears the filter from the table, but not in the selected textbox.
I found out that there is this property
[showClear]="true"
That adds an X at the end of the textbox that clears it out. Sadly, the styling/positioning is not what I need.
What could be the ways to fix the clear button ? Add a ts function to clear out the selected values? If so, how to bind it to the clear button because it is generated from
<p-columnFilter
display="menu"
menu property and I had no luck to find the way to try add/change functionality to that button.
This is a circular menu. In the options to open with the touch on the floating button but I get :
ERROR TypeError: Cannot read property 'getElementById' of undefined
when I run my code. Also the menu is already open when I load this page. I want it to be closed and open when it's clicked on.
<a class="floating-btn" (click)="document.getElementById('circularMenu1').classList.toggle('active');">
<a><ion-icon name="menu"></ion-icon></a>
</a>
<menu class="items-wrapper">
<ion-icon name="home"></ion-icon>
<ion-icon name="person"></ion-icon>
<ion-icon name="heart"></ion-icon>
<ion-icon name="help"></ion-icon>
</menu>
</div>
please use this approach
in html
<a class="floating-btn" (click)="toggleMenu()">
<a><ion-icon name="menu"></ion-icon></a>
</a>
<menu [ngClass]="{'active': isOpen}">...</menu >
in ts
isOpen = false; // set it to false initially
toggleMenu(){
isOpen = !isOpen; // toggle it as you want
}
From your code, I'm unable to find the ID which you have mentions in that click event. Btw this is not a good practice to use en angular. As a solution, for the click event, you can call a function in the controller and set a variable based on the condition. Then after you can use NgClass property binging in order to close or open the menu.
Here is the reference for NgClass property.
Execution:
I have several Material Checkboxes in a Material Dialog Component. They represent a column filter for a table:
<h1 mat-dialog-title>Filter</h1>
<div mat-dialog-content>
<ng-container *ngFor="let column of allColumns; index as i; first as firstEntry ">
<mat-checkbox *ngIf="!firstEntry" class="checkbox" [checked]="checkedList[i]" [aria-label]="column" (click)=doToggle(i)>{{column}}</mat-checkbox>
</ng-container>
</div>
<div mat-dialog-actions>
<button mat-button (click)="onNoClick()">Abbrechen</button>
<button mat-button [mat-dialog-close]="allColumns" cdkFocusInitial>Reset</button>
<button id="ok-button" mat-button [mat-dialog-close]="displayedColumns" cdkFocusInitial>Ok</button>
</div>
When I click on a Checkbox I want to check it. All booleans of the Checkboxes are saved in a boolean array named checkedList. When I click on a Checkbox the method doToggle(i) gets executed.
doToggle(i: number){
if(this.checkedList[i]){
this.displayedColumns[i] = this.allColumns[i];
}
else{
this.displayedColumns[i] = null;
}
this.checkedList[i] = !this.checkedList[i];
}
The method also fills or empties the values at the appropriate position of the column list. At the end of the method it negates the boolean at the appropriate position in the checkedList.
Problem:
I always have to click twice on the Checkbox to check or uncheck it. The values are added or removed properly. But still I have to click two times on the checkbox. Why is that?
Try sending the value of checkbox in the click event.
Add template reference variable(#ck) to checkbox and get its value ck.checked
[checked]="checkedList[i]" [aria-label]="column" #ck (click)="doToggle(i,!ck.checked)"
and in doToggle function
doToggle(i,value){
this.checkedList[i] = value;
if(this.checkedList[i]){
this.displayedColumns[i] = this.allColumns[i];
}
else{
this.displayedColumns[i] = null;
}
}
in angular 2 there is a button that I want when click on it a div appear.
<button class="dokme" type="button" (click)="onSelect(signUp)" >Register</button>
<div *ngIf="selectedBtn">
<div>Hello</div>
</div>
and I couldn't complete my component, because I don't know how I should write it:
onSelect():void{
this.selectedBtn=...(?)}
Actually I know it can be similat to "Hide the empty detail with ngIf" in angular tutorial Hide the empty detail with ngIf, but the problem is I can't change that code to what I want. Because in that example there is hero and I don't know what should I replace it.
please help me in the simplest way it would be your kind.
The expression you pas into (click) will be executed when you click on the button.
If the expression you pass into *ngIf is true, the content inside the element will be present on the page. Otherwise, it will not.
So, what you ned to do is to change the value of selectedBtn when (click) event happens.
Template
<button class="dokme" type="button" (click)="onSelect()" >Register</button>
<div *ngIf="selectedBtn">
<div>Hello</div>
</div>
Component
onSelect() {
this.selectedBtn = true
}
Just set the variable to true
onSelect() {
this.selectedBtn = true;
}
ngIf works in a simmilar way that if statement in other programming languages so it checks for condition and if it is true (or if a function called in condition returns true). In this case, your ngIf is linked to component variable selectedBtn so only what you need to do is set it to true:
this.selectedBtn = true;
More easily, you can achieve the sane goal without creating new function in your controller.
<button class="dokme" type="button" (click)="selectedBtn=true" >Register</button>
<div *ngIf="selectedBtn">
<div>Hello</div>
</div>
Or if you want the button to toggle :
<button class="dokme" type="button" (click)="selectedBtn=!selectedBtn" >Register</button>
<div *ngIf="selectedBtn">
<div>Hello</div>
</div>
I've got an irritating problem with data binding using ng-model and button.
The principle of operation of my site:
My HTML site displays a list of projects (loaded from external .json file).
Each row has a button named Edit which displays a modal containing some <input type="text" filled with relevant data about project (like project.name, project.date etc.)
Initial value of input is equal to object data (text-input called Name will contain project.name etc.)
Object is modified only if you click Save button and confirm the operation (confirm(sometext) is okay).
Closing the modal, not clicking the button or pressing cancel on confirmation box should prevent data from being updated.
Editing input (let's say that project.name is "Project2" and I modify it by adding 3 numbers resulting in "Project2137"), closing modal and opening it again should result in "Project2" text inside input (because object wasn't modified, only input)
So far I understand that single text input should look like this
<input type="text" id="editName" class="form-control" ng-model = "project.name">
Using ng-model means that they are binded. That's what I know. However editing input means that object is updated as soon as I enter some data.
I tried to fiddle with ng-model-options but I didn't find any possible solutions.
I tried to do it programmatically as well using
<input type="text" id="editName" class="form-control" value = {{project.name}}>
....
<button type="button" class="btn pull-right btn-primary btn-md" ng-click="edit(project)" data-dismiss="modal" >Save</button>
And function:
$rootScope.edit = function(project)
{
if(confirm("Are you sure to save changes?"))
{
project.name = angular.element(document.getElementById('editName')).val();
// ...and so on with other properties
This solution is kinda close to what I wanted to achieve (object is updated only on confirm), but I faced another problem: input loads data from object only once at the beginning instead of each time the modal is opened which is against rule #5
Is there any way to fix this using either ng-model bind or custom function? Or maybe there is some other, easier way?
--EDIT--
Here I don't have any problem with saving the data using a button, everything works well and clicking Save is reflected in a projects list. (well until I hit a F5 key).
The problem is that input text is not properly binded to project and that's what I want to fix.
Sample data (pseudocode)
project1.name = "Proj1"
project2.name = "Proj2"
I click an Edit button on row #1
Text input displays "Proj1". Everything is fine.
I change input by adding some random characters like "Proj1pezxde1"
Text input is now "Proj1pezxde1"
I do not click Save button.
I close the modal.
Project summary still displays "Proj1". Okay.
I click an edit button on first row
10. Text input is "Proj1pezxde1" even though I didn't modify an object.
Text input should read data from object again (each time I open this modal) and thus display "Proj1"
That's the problem I want to fix. Sorry for being a little bit inaccurate.
You can create a copy of the project object in modal controller and use this object to bind with the input element of the modal
$scope.copyProj = angular.copy($scope.project);
Assign the copy object properties to project only when save is clicked.
As per my understanding after reading the provided descriptions, you have a list of projects, which is being used as in an repeater and you want to bind each projects data to a Text box and a Button.
Have you tried initializing your Projects object following way?
$scope.projects = [
{ 'name': 'proj1', 'id': '1' },
{ 'name': 'proj2', 'id': '2' }
];
Then you can do something like below to show your data
<div ng-repeat="project in projects">
<div>
<input type="text" class="form-control" ng-model = "project.name">
<button type="button" class="btn pull-right btn-primary btn-md" ng-click="edit(project)" data-dismiss="modal" >Save</button>
</div>
</div>
The simplest way to do this in my opinion is using a second object that is a copy of the project, and after confirmation applying the changes to the original project object.
For example, a simple "pseudo code" of a controller:
function MyCtrl($scope) {
$scope.projects = [...];
$scope.currentProject = null;
$scope.edit = function(project) {
$scope.currentProject = angular.copy(project); // This will create a copy so the changes in $scope.currentProject will not reflect.
// Open dialog with input bound to $scope.currentProject
if (confirm) {
// Assign all properties from currentProject to project
angular.extend(project, $scope.currentProject);
}
}
}
So , as I understand from your question , you need to update the project data only if it is saved. To do that you can maintain a copy of the actual object which get updated only it is saved like below :
Here we are using angular.copy(), which does a deep copy of the source object.
$scope.original = {name : "xyz"};
$scope.project = angular.copy(original);
//Call this when the user confirms to save , here we are replacing the
//original copy with the latest object that needs to be saved.
$scope.save = function () {
$scope.original = angular.copy($scope.project);
}
//Call this when closing the modal or clicking cancel or when losing
//focus, this will reset the changes to the original copy.
$scope.reset = function () {
$scope.project = angular.copy(original);
}