Angular2中*ngIf绑定变量后未隐藏DOM元素,求排查错误
Got it, let's work through why your <div> isn't hiding even though the console says isPickupOrderAvaliable is false. There are two key, super common Angular pitfalls here:
1. Unnecessary this. in the Template
Angular templates automatically have access to your component's properties without needing this. — using it here can cause unexpected binding glitches, even if it looks like it should work.
Your original template line:
<div *ngIf="this.isPickupOrderAvaliable">
Fix it by stripping out this.:
<div *ngIf="isPickupOrderAvaliable">
2. String vs. Boolean Type Mismatch
The console showing "false" doesn't always mean it's a boolean false — it could be a string "false". In JavaScript/Angular, non-empty strings count as "truthy" values, so *ngIf will keep the <div> visible even if the string is "false".
Looking at your submitPickupOrder() method: you're assigning x._body directly to this.isPickupOrderAvaliable. If your HTTP response returns plain text (like "false" instead of a JSON boolean), you need to convert it to a proper boolean value.
Fixed TypeScript Code
submitPickupOrder() { // Validate form first if (!this.pickupOrderForm.valid) { console.log("Form validation failed"); return; } this.http.post("your-api-endpoint", this.pickupOrderForm.value) .subscribe((response) => { // Option 1: If response is plain text "true"/"false" this.isPickupOrderAvaliable = response._body === "true"; // Option 2: If response is JSON (better practice!) // const responseData = JSON.parse(response._body); // this.isPickupOrderAvaliable = !!responseData.isPickupOrderAvaliable; console.log(typeof this.isPickupOrderAvaliable); // Should log "boolean" now }); }
Quick Post-Fix Check
After making these changes, confirm two things in your browser console:
- The value of
isPickupOrderAvaliableis a boolean (not a string) - The template's
{{isPickupOrderAvaliable}}output showsfalse(not"false")
These tweaks should make the *ngIf correctly hide the <div> when the value is false.
内容的提问来源于stack exchange,提问作者allpacka

