Issue
Here is my code
I am having List Array like: this is getCall.
ktsessions =
[ {"presenter":"Bharath","topic":"Angular","status":"scheduled","emailId":"bharathkumar@gmail.com"}, {"presenter":"Sayyad","topic":"Angular","status":"organized","emailId":"raheemsayyad@gmail.com"},{"presenter":"Kanchan","topic":"APS","status":"scheduled","emailId":"kanchanubey@gmail.com"} ];
<tr *ngFor = "let ktsession of ktsessions >
<td ><input type="checkbox" [disabled]='disabled'></td>
</tr>
TS code:
getktsession(){
this.service.getKtsession().subscribe(data =>{
console.log('get', data);
this.ktsessions = data;
this.ktsessions.find(user => {
if(user.presenter ==="Kanchan"){
this.disabled = true
} else {
this.disabled = false;
}
});
});
}
Solution
There are several issues here.
<tr *ngFor = "let ktsession of ktsessions >
– Missing closing quote afterktsessions
<td ><input type="checkbox" [disabled]='disabled'></td>
–[disabled]='disabled'
should be[disabled]="ktsession.disabled"
. Each checkbox instance needs to have its owndisabled
property.[disabled]='disabled'
sets each checkbox’sdisabled
property to thedisabled
property of the component class instance rather than the checkbox instance.this.ktsessions.find(user => {
– Array#find is not an appropriate method to use here, even though it happens to work since you’re not returning anything from the callback function and it will therefore iterate the entire array. Array#find is for searching an array for an element that matches the specified criteria and returning that element, not for iterating over an array and setting properties on each element, which is what you’re doing here. Array#forEach is the appropriate method for that.this.disabled = true
andthis.disabled = false
– these are setting thedisabled
property on the component class instance (which is whatthis
refers to), but what you need to do is set thedisabled
property on eachuser
instance:user.disabled = true
oruser.disabled = false
.
So your template should look something like this:
<tr *ngFor="let ktsession of ktsessions">
<td>
<input type="checkbox" [disabled]="ktsession.disabled" /> <!-- reference "ktsession.disabled" instead of "disabled" -->
{{ ktsession.presenter }}
</td>
</tr>
And your subscribe
should look something like this:
this.getKtsession().subscribe((data) => {
this.ktsessions = data;
this.ktsessions.forEach((user) => { // <-- use forEach, not find
if (user.presenter === 'Kanchan') {
user.disabled = true; // <------------ set user.disabled, not this.disabled
} else {
user.disabled = false; // <----------- set user.disabled, not this.disabled
}
});
});
Here’s a StackBlitz showing it working with those changes.
Answered By – MikeJ
Answer Checked By – Robin (AngularFixing Admin)