在使用angualr开发项目操作不建议直接使用原生的document进行操作,可以使用ViewChild属性装饰器操作dom对象。
操作案例:
1. 在app.components.ts文件中引入 ViewChild, ElementRef
import { Component,ElementRef,ViewChild } from '@angular/core';
2. 定义引用变量,然后写一个方法进行调用
@ViewChild('file')
file: ElementRef
uploadFile(){
let file = this.file.nativeElement.files[0]
console.log("上传文件:"+ file)
}
3. 打开app.component.html在input上传文件标签,在对应标签上添加 #file。如图所示
4. 保存代码后打开浏览器,按F12后上传一个文件,即可看控制台上打印出文件的信息