のための変化検出タイミング:Angular2:私はチャット表示するための簡単な自動スクロールの指示に取り組んできました自動スクロールディレクティブ
@Directive({
selector: "[autoScroll]"
})
export class AutoScroll {
@Input() inScrollHeight;
@Input() inClientHeight;
@HostBinding("scrollTop") outScrollTop;
ngOnChanges(changes: {[propName: string]: SimpleChange}) {
if (changes["inScrollHeight"] || changes["inClientHeight"]) {
this.scroll();
}
};
scroll() {
this.outScrollTop = this.inScrollHeight - this.inClientHeight;
};
}
は、このディレクティブは、私が設定したときに動作しますenableProdMode()
とするときChangeDetectionStrategy
はデフォルトに設定されていますが、「devモード」では例外が発生します。 ChangeDetectionStrategy
をonPush
に設定することができます。その場合、例外は発生しませんが、スクロールは遅れます。
Domを更新してからScroll関数を呼び出すことができるように、このコードを構造化する方法はありますか?私はsetTimeout()
を試しましたが、遅延が悪化し、ChangeDetectorRef
を使って試してみて、observableを購読してmarkForCheck()
をトリガーしました。 ngAfterViewChecked()
を使用すると、ブラウザがクラッシュします。
@Component({
selector: "chat-display",
template: `
<div class="chat-box" #this [inScrollHeight]="this.scrollHeight" [inClientHeight]="this.clientHeight" autoScroll>
<p *ngFor="#msg of messages | async | messageFilter:username:inSelectedTarget:inTargetFilter:inDirectionFilter" [ngClass]="msg.type">{{msg.message}}</p>
</div>
`,
styles: [`.whisper {
color: rosybrown;
}`],
directives: [NgClass, AutoScroll],
pipes: [AsyncPipe, MessageFilterPipe],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChatDisplay implements OnInit {
username: string;
@Input() inSelectedTarget: string;
@Input() inTargetFilter: boolean;
@Input() inDirectionFilter: boolean;
messages: Observable<ChatType[]>;
constructor(private socketService_: SocketService, private authService_: AuthService) {
this.username = this.authService_.username;
};
ngOnInit() {
}
}
これは、DEVモードで起動される例外です。
例外:式 '1 @ ChatDisplayでthis.scrollHeight:40には、' それが確認した後に変更されました。以前の値: '417'現在値: '420' [this.scrollHeight ChatDisplay 1 @:40]で angular2.dev.js(23083,9)
は「例外」が実際には何か興味深いものになるだろう。 –
devモードで変更検出が2回発生し、チェックの間に "this.scrollHeight"という表現が異なります。観察可能なメッセージがディスプレイに表示されているように、これはscrollHeightを増加させるので、それはチェックの間で異なります、私はそれが起こっていると思います。 – dppower
質問に正確なエラーメッセージを追加できますか? –