代碼
模板文件
<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" (change)="fileInputChange(fileInput)" multiple #fileInput />
這行代碼最后的 #fileInput 代表在這個組件中定義一個變量 fileInput ,這個變量就代表了 這個input對象 ,在使用時和使用模板變量沒有差別,但是要注意定義這個模板變量的作用域,不是在你的組件中定義的,你這個組件就可以到處都能使用的,如是你使用了一個第三方的組件,這個組件允許你在組件標簽內寫一些模板代碼,如是你在這個第三方組件的內部定義的這個引用變量,這個第三方組件的外部就不能用這個引用變量
除了可以將標簽元素賦值給模板引用變量外,還可以將一個組件引用賦值給模板引用變量(如是這個組件/指令導出了),[官方例子]['https://angular.cn/guide/forms#show-and-hide-validation-error-messages']
<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">使用時, 可以通過 name變量訪問更多的參數,比如 這個input 是否被點過(touch),是否被賦值過(dirty)等等;
廣州設計公司https://www.houdianzi.com 我的007辦公資源網站https://www.wode007.com
在組件中使用箭頭函數與匿名函數的區別
區別主要在於 上下文的this指向的目標不一樣
箭頭函數中的this 指向的是這個組件實例,匿名方法 指向的是這個方法 的調用方
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方法 如果這樣寫
fileReader.onload = function(ev) { const data = fileReader.result.toString(); this.icon = data; };
那么 this 指的就是fileReader,因為是這個對象調用了 它自己的onload,也就是這個匿名方法;這時頁面上不會體現出你選擇了新的圖片,因為你沒有 為組件的 icon屬性賦值,而是給fileReader的icon屬性賦值了
如是使用箭頭函數,那么this指的就是組件本身