【Angular】 화상을 읽어서 표시한다
                                            
                                                
                                                
                                                
                                                
                                                
                                                 8756 단어  Angular
                    

간단하게 입력 버튼
<!-- 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
입력 버튼 이외를 클릭하여 선택 창을 표시하고 싶을 때

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()를 작동시켜 주는 것으로 선택 윈도우를 열 수가 있습니다.
Reference
이 문제에 관하여(【Angular】 화상을 읽어서 표시한다), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/frtklog/items/55ea3ab56e7474494368텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)