1
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.

AngularJSでimgタグが壊れた時、ngOnを使う

Last updated at Posted at 2020-01-24

TL;DR

  • imgタグが壊れた時のエラーハンドルをngOnを使用する

環境

  • AngularJS 1.7.9(ドキュメント見ると、1.7以上から)

imgタグが壊れた時、ngOnなしの場合

userIdを渡せば、ユーザー画像を表示するようなコンポーネントがあるとします

例えば、アカウント削除でuserIdが返ってこないとか、オフラインとか何らかの理由でリクエストが失敗すると
このような代替画像を表示させるはずです

nophoto.png

imgタグのsrcにセットした画像が取得できない場合、
・テンプレート側で壊れた画像を補う
・CSS側で補う
・JSで補う

など、特にベストプラクティスとかありそうもないので、特段の理由なくコントローラーでエラーハンドルしてました

html側でimgタグのonerrorも試したりしましたが、
答えが出なかったので、パッと見て何したいかかわかるコードで対応してました・・・

(new imageしてインスタンス作るまでするか?とか葛藤はありましたが)

しかし問題点

AngularのライフサイクルかJSにうまく乗れておらず、下記のような↓一瞬壊れた画像が表示されたあとで、代替画像が表示されていました、一瞬だったので目をつむっていました・・・

スクリーンショット 2020-01-24 16.16.35.png

ngOnを使って克服

AngularJS1.7以上から実装されたngOnで下記のように変更しました:santa:

user-image.pug
img.user-image(ng-on-error="ctrl.onError()" ng-src="{{ ctrl.userImageUrl }}" alt="ユーザー画像")
user-image.component.ts
const noPhoto = require('_Images/no-photo.jpg');

class UserImageComponent {
  private userId: string; //bindings
  private userImageUrl: string; //view bind

  $onChanges = changes => {
    if (!changes.userId.currentValue) return;
    const url = `https://hoge/thumbnail/${this.userId}.jpg`;
    this.userImageUrl = url;
  };

  onError = () => {
    this.userImageUrl = noPhoto;
  };
}

export const userImage = {
  template: require('./user-image.pug'),
  controllerAs: 'ctrl',
  controller: UserImageComponent,
  bindings: {
    userId: '<',
  },
};

ポイント

  1. テンプレート側でng-on-errorをカスタム属性で付与し、imgタグが壊れた時にonErrorが発動するように変更
  2. onErrorで代替画像に差し替える

だけ:santa:

これで圧倒的に直感的になり、画像も壊れたのが表示されなくなりました:santa:

Angularにも同様のやつあるんですかね?:santa:

参考

ngOn

あとがき

$onInit時に、userIdがundefindで渡ってくるときがあるので、$onChangesを使っています:santa:

1
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
1
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?