LoginSignup
4
4

More than 5 years have passed since last update.

Angularでビューに基づく(DOMの高さとか)処理を実行する

Posted at

はこです、こんにちわ。

DOMに表示した内容によって処理を変えたいことがあると思います。
clientHeightやscrollHeightに応じて(あるいはclientWidth/scrollWidth)、省略表示したり、です。
(と言うか他の用例が思いつかなかった・・・他の用例あれば、是非コメントください)。

そんなとき、こんな風にします。

動くが、エラーが出る

my-component.html
<div #myDiv>
   <!-- 長さバラバラなコンテンツ -->
   {{ content }}
</div>

<!-- コンテンツの高さ(height)が100px以上なら、「省略されました」とか出したい -->
<button *ngIf="myDiv.clientHeight > 100">省略されました。もっと読むには押してください</button>

コレで動きますが、 ExpressionChangedAfterItHasBeenCheckedError というエラーが出ると思います。

エラーのでないきちんとした書き方

ビューに関する処理は、ngAfterViewChecked() の中で処理するようにします。

my-component.html
<div #myDiv>
   <!-- 長さバラバラなコンテンツ -->
   {{ content }}
</div>

<!-- コンテンツの高さ(height)が100px以上なら、「省略されました」とか出したい -->
<button *ngIf="readmoreButtonEnnabeld">省略されました。もっと読むには押してください</button>

my-component.ts
import { Component, OnInit, ViewChild, AfterViewChecked, ElementRef } from '@angular/core';


export class MyComponent implements OnInit, AfterViewChecked {

  @ViewChild('myDiv') myDiv: ElementRef;
  readmoreButtonEnnabeld = false;
  content = ''

  ngOnInit() {
    this.content = '何か長い文字列...'
  }

  ngAfterViewChecked() {
    this.readmoreButtonEnnabeld = this.myDiv.nativeElement.clientHeight > 100;
  }

}




4
4
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
4
4