查看不更新基类更改

时间:2017-09-13 15:42:41

标签: angular

我正在使用Angular 4.我有一个基类,它有一个受保护的变量,当它被切换时在视图中没有变化。为了传播事件需要做些什么?

这是我的基类:

export class MyBaseComponent {
    protected showCDNumbers: boolean = false;

    toggleCDNumberVisibility() {
        this.showCDNumbers = !this.showCDNumbers;
    }
}

这是继承自base的类:

export class MyComponent extends MyBaseComponent {

}

以下是观点:

<div>{{showCDNumbers}}</div>
<a (click)="toggleCDNumberVisibility()">Toggle</a>

2 个答案:

答案 0 :(得分:0)

您可以尝试此操作以查看视图是否在toggleCDNumberVisibility()方法调用时更改。通过ChangeDetectorRef@angular/core库中的constructor注入两个类(父级和子级),并使用其detectChanges()方法。

  

BaseComponent

import { ChangeDetectorRef } from '@angular/core'

protected showCDNumbers: boolean = false;

constructor (protected ref: ChangeDetectorRef) {}

toggleCDNumberVisibility() {
 this.showCDNumbers = !this.showCDNumbers;
 this.ref.detectChanges();
}
  

ChildComponent

import { ChangeDetectorRef } from '@angular/core'

constructor (protected ref: ChangeDetectorRef) {
 super(ref);
}

答案 1 :(得分:0)

略有不同的版本:

export class MyBaseComponent {
    protected showCDNumbers: boolean = false;
  constructor(value){
    this.showCDNumbers=value;
  }

    toggleCDNumberVisibility() {
        this.showCDNumbers = !this.showCDNumbers;
    }
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent extends MyBaseComponent{
  name = 'Angular 4';
   constructor(){
     super(true);
   }
    toggleCDNumberVisibility() {
      super.toggleCDNumberVisibility();
    }

}

DEMO