这是一个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); } }
<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