首页 > 解决方案 > 屏幕方向更改更新文本

问题描述

看法:

<Label [text]="name"></Label>

零件:

import {  Component } from '@angular/core'
import * as screenOrientation from '@nativescript/core/application';

@Component({
 selector: 'ns-new',
 templateUrl: './new.component.html',
 styleUrls: ['./new.component.css'],
})

export class NewComponent {

  name:string = "Not Rotated";
  constructor( ) {
    screenOrientation.on("orientationChanged", this.onOrientationChanged)
  }

  onOrientationChanged = (evt) => {
    console.log("old name " + this.name);
    this.name="Rotated";
    console.log("new name " + this.name);
  }
}

当屏幕旋转时,文本不会改变。

有谁知道我错过了什么,或者问题出在哪里?

标签: angularnativescript

解决方案


我认为问题在于,当您在“外部”Angular 进行更改时,您需要指示 Angular 发生了更改(*)。为此,您需要使用 ngZone

//in constructor you inject ngZone
constructor(private ngZone: NgZone) { }

//when a change outside Angular happens

onOrientationChanged(evt) => {
  //this line happens outside Angular
  console.log("old name " + this.name);

  this.ngZone.run(() => {  //but these another run in Angular
      this.name="Rotated";
      console.log("new name " + this.name);
  })
})

(*) 典型情况是 javaScript 中的调用或 Cordova 中的事件


推荐阅读