LoginSignup
3
5

More than 3 years have passed since last update.

【Angular】画像を読み込んで表示する

Last updated at Posted at 2020-06-23

ファイルを選択して画像のプレビューを表示するサンプル
スクリーンショット 2020-06-23 15.44.17.png

シンプルにinputボタン

<!-- html -->
<div class="upload">
    <input type="file" accept="image/*" 
           (change)="onChangeFileInput($event)">
    <img [src]="imgSrc" alt="">
</div>
import { Component, OnInit } from '@angular/core';

export class ImageUploadComponent implements OnInit {

  file: File = null;
  imgSrc: string | ArrayBuffer = "";

  constructor() { }

  ngOnInit() {}

  onChangeFileInput(event) {

    //fileが選択されていなければリセット
    if (event.target.files.length === 0) {
      this.file = null;
      this.imgSrc = "";
      return;
    }

    //ファイルの情報をfileとimgSrcに保存
    let reader = new FileReader();
    this.file = event.target.files[0];
    reader.onload = () => {
      this.imgSrc = reader.result;
    }
    reader.readAsDataURL(this.file);
  }
}

FileReaderについて…MDN web docs

inputボタン以外をクリックして選択ウィンドウを表示したいとき

スクリーンショット 2020-06-23 16.01.30.png
Adivとか画像とか、input以外の要素をクリックしてウィンドウ表示させたいとき

<div class="upload">
    <input 
      type="file"
      style="display: none;" <-追加
      #fileInput  <-追加
      accept="image/*"
      (change)="onChangeFileInput($event)"
    >
    <div class="div-upload" (click)="onClickFileInputButton()">アップロード</div> <-追加
    <img [src]="imgSrc" alt="">
</div>
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

export class ImageUploadComponent implements OnInit {

  @ViewChild("fileInput", { static: false }) fileInput: ElementRef; //追加
  file: File = null;
  imgSrc: string | ArrayBuffer = "";

  constructor() { }

  ngOnInit() {}

  onClickFileInputButton(): void { //追加
    this.fileInput.nativeElement.click();
  }

  onChangeFileInput(event) {
    //--- 変更なし ---
  }
}

ViewChildについて…【Angular】@ViewChild / @ViewChildren を理解する【v6.x】
inputは非表示にしつつ、ViewChildを使いts側からinputの操作をできるようにします。
ボタンにしたい要素をクリックした時に、inputに対しclick()を作動させてあげることで選択ウィンドウを開くことができます。

3
5
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
5