Reputation: 919
Angular 5.2.0 and TypeScript 2.6.2.
I'm using the following plugin to read NFC tags. The listener starts when user presses button.
<button (tap)="doStartNdefListener()" text="Get NFC"></button>
<Label [text]="nfcText" textWrap="true"></Label>
The problem - even though the callback in doStartNdefListener() successfully scans for tag, saves the output in nfcText, outputs values from within callback, even though the value for nfcText has been changed, it does not update the UI.
import { Component } from "@angular/core";
import { Nfc, NfcTagData, NfcNdefData } from "nativescript-nfc";
export class StartComponent {
public nfc: Nfc;
public nfcText: string;
constructor(){
this.nfc = new Nfc();
}
public doStartNdefListener() {
this.nfc.setOnNdefDiscoveredListener((data: NfcNdefData) => {
if (data.message) {
let tagMessages = [];
data.message.forEach(record => {
tagMessages.push(record.payloadAsString); });
console.log(tagMessages.join(", "));
this.nfcText = tagMessages.join(", ");
console.log(this.nfcText);
}
},
{ stopAfterFirstRead: true, scanHint: "Scan the tag!" })
.then(() => this.nfcText = "Listening for tag")
.catch(err => alert(err));
}
}
Both console outputs print out the scanned NFC tag value, but the label does not get updated.
Edit:
What is interesting is that UI updates after I execute another function after I've ran doStartNdefListener() function.
Upvotes: 1
Views: 739
Reputation: 57971
@rgantla, the problem is that Angular don´t take acount the change (don't refresh the labels). So, make a function
private changeNfcText (message:string) {
this.ngZone.run(()=>{
this.nfcText = message;
});
}
}
Then,
this.nfc.setOnNdefDiscoveredListener((data: NfcNdefData) => {
if (data.message) {
let tagMessages = [];
data.message.forEach(record => {
tagMessages.push(record.payloadAsString); });
console.log(tagMessages.join(", "));
this.changeNfcText(tagMessages.join(", ")); //<--call the function
console.log(this.nfcText);
}
},
{ stopAfterFirstRead: true, scanHint: "Scan the tag!" })
.then(() => this.changeNfcText("Listening for tag")) //<--call the function
.catch(err => alert(err));
}
Upvotes: 3
Reputation: 1956
Have you tried the below approach?
<Label> {{nfcText}} </Label>
I cannot recall if there exists a text property on the label that you can bind to, but surely, you can use string interpolation to output your text to the view.
Upvotes: 0
Reputation: 820
Try wrapping that into a $timeout block.
$timeout(()=> {
this.nfcText = tagMessages.join(", ");
}, 100);
This will force a digest cycle that will make your UI notice the change.
Upvotes: -1