在Angular 2中,直到鼠标悬停,组件变量才会在视图中更新

Component variable change not updated in view until mouseover in Angular 2

本文关键字:更新 变量 组件 视图 鼠标 Angular 悬停      更新时间:2023-09-26

从angular2-alpha更新到最新版本后,布尔值的更改不会更新*ngIf,直到执行某些操作。

这是有问题的组件:

declare var CKEDITOR: any;
export class FieldComponent {
 @Input() field: any = {};
 ckeditor: any;
 editable: boolean = false;
 constructor(){
  this.switchToUnEditable();
  this.listenForEvent("FieldEditableEvent", (data) => {
    this.switchToEditable();
  });
 }
 switchToEditable(){
  this.ckeditor.destroy();
  this.ckeditor = CKEDITOR.replace(this.field.id);
  this.editable = true;
 }
switchToUnEditable() {
  if(this.ckeditor) {
   this.ckeditor.destroy();
  }
  this.ckeditor = CKEDITOR.replace(this.field.id, {
   toolbar: []
  })
  this.editable = false;
 }

}

下面是这个组件的模板:

<div *ngIf="editable" class="green-background white-text unlocked">
  This field is unlocked!
  <button (click)="switchToUnEditable()"> 
   Save and close. 
  </button>
</div>
<div *ngIf="!editable" class="red-background white-text locked">
  This field is locked!
</div>
<textarea [attr.name]="field.id" [(ngModel)]="field.value">  
</textarea>

这在更新之前工作得很好-现在我必须将鼠标移到div内的按钮上才能在视图中应用*ngIf。

或者,我可以在组件树的更上层执行一个事件,而*ngIf也将在那个点上应用。例如,打开侧边导航会将视图从锁定更改为未锁定

这是Angular 2中期望的正确的变更检测吗?如果是,我如何让用户在执行更新视图的事件之前意识到该字段是锁定的未锁定的呢?

似乎对switchToEditable()switchToUnEditable()的调用是在angular区域之外进行的。

如果你显式地调用变更检测,它应该工作:

constructor(private cdRef:ChangeDetectorRef) {}
switchToEditable(){
  this.editable = true;
  this.cdRef.detectChanges();
}
switchToUnEditable() {
  ...
  this.editable = false;
  this.cdRef.detectChanges();
}