3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

画面更新処理の呼出タイミング

Posted at

趣旨

angularで外部サービスからデータを取得した後、viewに反映するとして。
viewに反映する内容をJqueryで動的に更新したい時の注意点です:grinning:

ライフサイクルイベントに頼らない

NG:ライフサイクルイベントでJQuery呼び出し

  • OnChanges利用→サービス呼び出しが完了するより前に終わってしまう
  • DoCheck利用→DoCheckによるview更新を自分で拾って無限ループ
  • AfterViewInit利用→view反映より先に終わってしまう
  • AfterViewChecked利用→AfterViewCheckedによるview更新を自分で拾って無限ループ

OK:サービス呼び出し完了とともにJQuery呼び出し

history.component.html
<div class="history-table">
    <table class="history-body">
        <tbody>
            <tr *ngFor="let record of lodossWar">
                <td>{{record.Year}}</td>
                <td>{{record.Event}}</td>
            </tr>
        </tbody>
    </table>
</div>
historyComponent.ts
import {
  Component,
  Input,
  OnChanges,
} from '@angular/core';

// jQuery用の変数宣言
declare var $;

@Component({
  selector: 'history-component',
  templateUrl: './history.component.html'
})
export class HistoryComponent implements OnChanges {
  @Input()
  actionMode: string;

  // 画面に表示するレコード
  private lodossWar;

  constructor(private recordService: RecordService) {}

  ngOnChanges() {
    if (this.actionMode === 'reload') {
        this.recordService
        .requestRecords()
        .subscribe(records => {
          // 検索結果をセット
          this.lodossWar = records;
          // JQuery呼び出し
          this.callJQuery();
        });
    }
  }

  private callJQuery() {
    // なんらかの処理
    $(function() {
      ...
      }
    });
  }
}

横着してライフサイクルイベントに任せようと考えるんじゃなくて
サービス呼び出しが完了したその場で処置しようねって事ですね:sweat:

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?