NativeScript中ListView的itemTap事件无法触发求助
Let's break down the most likely issues causing your itemTap event to fail, and walk through actionable fixes:
1. Button is Intercepting Touch Events (Most Common Cause)
Each list item includes a <Button>, and on Android, buttons consume touch events by default—this prevents the event from bubbling up to the ListView's itemTap handler.
Fix: Stop Event Propagation
You can handle this directly in the template:
<Button text="+" (tap)="addMesurement($event); $event.stopPropagation()" width="13%" ></Button>
Or update your addMesurement method to block the event from bubbling:
public addMesurement(event) { event.stopPropagation(); // Prevent the event from reaching the ListView item this.router.navigate(['/newMeasure']); }
2. Change Detection Issues with OnPush Strategy
Your component uses ChangeDetectionStrategy.OnPush, which means Angular only runs change detection when input references change or you manually trigger it. While you're reassigning this.myItems (which changes the reference), sometimes the update might not propagate immediately to the ListView.
Fix: Manually Trigger Change Detection
First, inject ChangeDetectorRef into your component:
import { ChangeDetectionStrategy, Component, OnInit, ChangeDetectorRef } from '@angular/core'; // ... constructor(private router: RouterExtensions, private cdRef: ChangeDetectorRef) { // Keep your existing constructor code }
Then call detectChanges() after updating myItems in the fetch method:
public fetch() { this.database.all('SELECT * FROM measures').then(rows => { this.myItems = []; for(let row in rows) { this.myItems.push({ 'id': rows[row][0], 'name': rows[row][1], 'unit': rows[row][2], 'today': rows[row][3], 'total': rows[row][4] }); } this.cdRef.detectChanges(); // Force Angular to update the view }); }
3. Bonus: Fix "No Measures Found!" Display
Your current ngOnInit code creates a Label instance but never adds it to the DOM, so the message won't show up. Replace that with template-based logic:
Add this below your ListView in home.component.html:
<Label *ngIf="myItems.length === 0" text="No Measures Found!" style="vertical-align: center; text-align: center; margin-top: 20;"></Label>
Then remove the unused Label creation code from ngOnInit:
public ngOnInit() { // Delete the entire if/else block here—we've replaced it with template logic }
Start with the button event propagation fix first—it's the most probable culprit for your itemTap not firing. If that doesn't resolve it, move on to the change detection adjustment.
内容的提问来源于stack exchange,提问作者Kristijan Jovanovic

