I am trying to show/hide div based on returned variable number, status variable always returns 1 or 2. but i get error in my html:
This condition will always return 'false' since the types '1' and '2' have no overlap.
what am i doing wrong?
.ts
status: number;
this.service.GetEstimationId(params['id']).subscribe(response => {
this.status = response.estimationStatus;
console.log(typeof this.status); // returns number
});
.html
<div *ngIf="status === 1">
<button (click)="toggleEdit(null, true)" type="submit" >
<i ></i> Send
</button>
<div *ngIf="status === 2">
<button (click)="toggleEdit(null, false)" type="submit" >
<i ></i> Save
</button>
</div>
CodePudding user response:
You are using ===
for checking the condition which is used for comparing two variables and also checks datatype.
You can change the type to number:
this.status = Number(response.estimationStatus)
or
use ==
instead.
*ngIf="status == 1"
Also seems that you forgot to close the first div
tag:
<div *ngIf="status === 1">
<button type="submit" >
<i ></i> Send
</button>
</div>
<div *ngIf="status === 2">
<button type="submit" >
<i ></i> Save
</button>
</div>
CodePudding user response:
Edit: It wasn't the problem. The real problem was in nesting two divs inside each other. I've posted my new answer here: https://stackoverflow.com/a/71495025/13523914
my old answer:
Seems like status is a string. I mean, you think it as 1 or 2 but it's actually "1" or "2". So there's two ways to solve it.
The best approach is to turn them to numbers. use
Number(status) === 1
You can forget type checking and let the type coercion happen. It's not best practice.
status == 1
CodePudding user response:
The only problem is that your two divs are nested, and the status can't be 1 and 2 at the same time. put the second div outside the first, and it will be solved.
<div *ngIf="status===1">
<button type="submit" >
<i ></i> Send
</button>
</div>
<div *ngIf="status===2">
<button type="submit" >
<i ></i> Save
</button>
</div>