LoginSignup
6
2

More than 5 years have passed since last update.

[Angular] src, srcset を設定するカスタムDirectiveを作成する

Last updated at Posted at 2018-07-06

カスタムコンポーネントは作っても、カスタムディレクティブは作ったことないという人も多いのではないでしょうか。

あんまり使う機会ってありませんが、例えば src, srcset を毎回Attributeに設定するのってだるいですよね。そういうときにカスタムディレクティブは役に立ちます

HTMLコードの Before After

こんな感じになります↓

<img src="/assets/images/icons/test/test.png" srcset="/assets/images/icons/test/test@2x.png 2x, /assets/images/icons/test/test@3x.png 3x">

<img appSrc="/assets/images/icons/test/test.png">

今回作成したDirective

import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[appSrc]',
})
export class SrcDirective {
  constructor(
    private el: ElementRef,
  ) {}

  @Input() set appSrc(path: string) {
    this.el.nativeElement.setAttribute('src', path);
    const pathWithoutExtension = path.replace(/\.[^\.]*$/, '');
    const extension = path.substring(path.lastIndexOf('.'));
    this.el.nativeElement.setAttribute('srcset', `${pathWithoutExtension}@2${extension} 2x, ${pathWithoutExtension}@3${extension} 3x`);
  }
}

仕様として、必ず 2x, 3x のものは、〇〇@2x.png のようなファイル名にすることを義務付けていはいますが、これでめんどうな src, srcset を簡単に速くかけます。

まとめ

Directive なんかよくわからないけど避けてきた人もいるのではないでしょうか。
今回の例のように、実は超簡単に強力なコードがかけます。

6
2
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
6
2