Angular中實現文件轉BASE64

Angular中實現文件轉BASE64

這是一個so easy的問題,主要是記錄一下angular 的模板變量的使用和組件中匿名方法 ,箭頭方法使用的區別javascript

代碼

模板文件

<div nz-col [nzSpan]="3">
          <!-- 設置爲 display: none ,由於 input看上去太醜 -->
          <input type="file" style="display: none" (change)="fileInputChange(fileInput)" multiple #fileInput />
          <!-- 由於 input 設置爲不可見,因此須要給用戶一個能夠觸發 input 的按鍵 -->
          <a (click)="choseIcon(fileInput)">
              <!-- img 的 src 屬性綁定 組件的 icon屬性的值,這個icon 屬性就是轉換後的base64串 -->
            <img alt="圖標" [src]="icon" class="menu-icon">
          </a>
  </div>

組件代碼

export class MenuEditComponent implements OnInit {
    icon = '';
    
    // 點擊按鍵時觸發 input的click方法 
    choseIcon(fileInput: any) {
        fileInput.click();
     }
    
    // 當選擇文件後會進入這個方法 
     fileInputChange(fileInput) {
  		  const file = fileInput.files[0];
  		  const fileReader = new FileReader();
  		  fileReader.onload = ev => {
  		    const data = fileReader.result.toString();
  		    this.icon = data;
  		  };
   		 fileReader.readAsDataURL(file);
      }
}

要點

如何將模板中的 DOM對象做爲參數傳入方法

<input type="file" style="display: none" (change)="fileInputChange(fileInput)" multiple #fileInput />html

這行代碼最後的 #fileInput 表明在這個組件中定義一個變量 fileInput ,這個變量就表明了 這個input對象 ,在使用時和使用模板變量沒有差異,可是要注意定義這個模板變量的做用域,不是在你的組件中定義的,你這個組件就能夠處處都能使用的,如是你使用了一個第三方的組件,這個組件容許你在組件標籤內寫一些模板代碼,如是你在這個第三方組件的內部定義的這個引用變量,這個第三方組件的外部就不能用這個引用變量java

除了能夠將標籤元素賦值給模板引用變量外,還能夠將一個組件引用賦值給模板引用變量(如是這個組件/指令導出了),[官方例子]['https://angular.cn/guide/forms#show-and-hide-validation-error-messages']typescript

<label for="name">Name</label>
<input type="text" class="form-control" id="name"
       required
       [(ngModel)]="model.name" name="name"
       #name="ngModel">
<div [hidden]="name.valid || name.pristine"
     class="alert alert-danger">
  Name is required
</div>

這一行代碼[(ngModel)]="model.name" name="name" #name="ngModel" 前面是雙向綁定沒什麼可說的,後面#name="ngModel 意思是將當前這個指令的的對象賦值給 name 變量,而後在這一行 <div [hidden]="name.valid || name.pristine" class="alert alert-danger">使用時, 能夠經過 name變量訪問更多的參數,好比 這個input 是否被點過(touch),是否被賦值過(dirty)等等;ide

在組件中使用箭頭函數與匿名函數的區別

區別主要在於 上下文的this指向的目標不同函數

箭頭函數中的this 指向的是這個組件實例,匿名方法 指向的是這個方法 的調用方ui

fileInputChange(fileInput) {
  		  const file = fileInput.files[0];
  		  const fileReader = new FileReader();
  		  fileReader.onload = ev => {
  		    const data = fileReader.result.toString();
  		    this.icon = data;
  		  };
   		 fileReader.readAsDataURL(file);
      }

這個方法 中 fileReader 的 onload方法 若是這樣寫this

fileReader.onload = function(ev) {
  		    const data = fileReader.result.toString();
  		    this.icon = data;
  		  };

那麼 this 指的就是fileReader,由於是這個對象調用了 它本身的onload,也就是這個匿名方法;這時頁面上不會體現出你選擇了新的圖片,由於你沒有 爲組件的 icon屬性賦值,而是給fileReader的icon屬性賦值了雙向綁定

如是使用箭頭函數,那麼this指的就是組件自己code

相關文章
相關標籤/搜索