Using NgZone to handle view updates
This is to show how to use zone.js to to handle view updates speech with the speech-recognition plugin
-
-
import {Component, NgZone} from '@angular/core'; import {SpeechRecognition, SpeechRecognitionTranscription,SpeechRecognitionOptions} from 'nativescript-speech-recognition'; @Component({ moduleId: module.id, selector: 'gf-main-ihm', templateUrl: 'main-ihm.html' }) export class MainIhmComponent { speechOptions: SpeechRecognitionOptions; public textSpeech:string constructor(private speech:SpeechRecognition, private ngZone: NgZone, ) { this.speechOptions = { locale: 'fr-FR', onResult: (transcription: SpeechRecognitionTranscription)=> { this.ngZone.run(() => { this.textSpeech = transcription.text; console.log(`${transcription.text}`); console.log(`${transcription.finished}`); }); } }; } writeText(){ this.speech.available().then(result =>{ result ? this.startListening() : alert('Speech recognition is not available'); }, error=>{ console.error(error); }) } startListening(){ this.speech.startListening(this.speechOptions).then(()=> { console.log("started listening") }, error=>{ console.error(error)}); } }
-
<StackLayout > <Button text="Talk " class="btn btn-primary main-btn main-btn-red font-awesome" (tap)="writeText()"> </Button> <Label class="gold card" textWrap="true" [text]="textSpeech"> </Label> </StackLayout>
-
@import 'nativescript-theme-core/css/lemon.css'; Page { background-color: #555555; } .card { margin: 10; padding: 5; vertical-align:top; background-color: #D3D3D3; border-width: 1; border-radius: 5; border-color: #232323; } .gold { background-color: #F0E68C; border-width: 1; border-radius: 5; border-color: #F0E68C; } .main-btn { border-width: 1; border-radius: 5; font-size: 26; height:120; } .main-btn-red { background-color: darkred; border-color: white; } .font-awesome { font-family: "FontAwesome"; }
-
I want to add a little detail concerning using "Speech Recognition with NativeScript Angular" presented previously here: https://nativescriptsnacks.com/videos/2017/05/06/speech-recognition.html. If we want to bind the "transcription text" with the label's text in the interface, the assignment shows inside an NgZone.