首页 文章

在Angular 2中鼠标悬停之前,组件变量更改未在视图中更新

提问于
浏览
6

从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中预期的正确更改检测 - 如果是这样,如何在执行更新视图的事件之前让用户知道该字段已被锁定或解锁 .

1 回答

  • 9

    似乎对 switchToEditable()switchToUnEditable() 的调用是以某种方式在Angulars区域之外进行的 .

    如果您明确调用更改检测,它应该工作:

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

相关问题