簡體   English   中英

如何在Angular2中觸發模型更改事件?

[英]How do I trigger an event on model change in Angular2?

我想在Angular2中構建一個類似於現有 Angular項目的鼓機

我構建組件的方法是讓SequencerComponent(父級)以指定的間隔(BPM)發出事件(@Output)。

// sequencer.component.ts
@Output() metronome = new EventEmitter();

  onBeat(count: number) {
    if(this.isPlaying) {
      this.beat.one = count == 1;
      this.beat.two = count == 2;
      this.beat.three = count == 3;
      this.beat.four = count == 4;

      this.metronome.emit(this.beat);
    }
  }

PadsComponent(child)偵聽此事件(@Input),然后如果PadComponent(grand-child)設置為active,則應播放聲音。

// pads.component.ts
export class PadsComponent {
  @Input() hit: any = {};
}

// pads.component.html
<pad [class.active]="hit.one" class="column pad"></pad>

<pad [class.active]="hit.two" class="column pad"></pad>

<pad [class.active]="hit.three" class="column pad"></pad>

<pad [class.active]="hit.four" class="column pad"></pad>

我可以讓類改變,但顯然我想做的不僅僅是HTML屬性綁定。 工作實例

如何讓孩子和大孩子在模型改變中運行功能? 是否有更好,更慣用的方法來解決這個問題?

我嘗試過使用ngDoCheck但我還沒有發現如何在這個用例中使用它。

更新hitsequencer.component.htmlbeat綁定如下:

<!-- sequencer.component.html -->
<div class="columns">
  <div class="column">
    <a class="button is-success" (click)="onPlay($event)" href="">Play</a>

    <a class="button is-danger" (click)="onStop($event)" href="">Stop</a>
  </div>
</div>

<pads [hit]="beat"></pads>

而不是@Input() hit: any = {}; 你可以有一個getter和一個setter for hit

private _hit;  // define a private variable _hit

@Input()
set hit(hit:any){  
    this._hit = hit;  // set the private variable and do whatever you want after each change
    playSomeSound(hit);
}
get hit(){  
    return this._hit;
}

您的模板代碼仍然相同,

<pad [class.active]="hit.one" class="column pad"></pad>
...

請查看此插件以獲取示例。

以下是如何使用ngDoCheck()監視模型更改並將其發出的示例:

ngDoCheck() {

  if (this.previousModel !== this.model) {
    this.modelChange.emit(this.model);
  }

  this.previousModel = this.model;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM