Angular如何将input文件上传模板变量传递给共享组件
实现方案
推荐优先使用事件通知的方案,逻辑更解耦,共享组件复用性更高,两种实现方式如下:
方案1:Output事件通知(推荐)
完全不需要传递DOM元素引用,逻辑分层更清晰:
- 第一步:修改共享组件2的代码
组件2 ts文件:
组件2 模板文件:import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-upload-button', templateUrl: './upload-button.component.html' }) export class UploadButtonComponent { // 定义点击按钮时触发的通知事件 @Output() uploadTriggered = new EventEmitter<void>(); }<button (click)="uploadTriggered.emit()">upload video</button> - 第二步:修改组件1的模板代码,直接监听事件触发input点击即可,不需要额外写ts逻辑:
<input type="file" accept=".mp4" #file /> <!-- 监听共享组件的上传触发事件,直接调用本地input的click方法 --> <app-upload-button (uploadTriggered)="file.click()"></app-upload-button>
方案2:Input传递DOM元素引用
如果确实需要把元素传递给共享组件操作,可以用该方案:
- 第一步:修改共享组件2的代码,定义Input接收文件输入框元素
组件2 ts文件:
组件2 模板文件:import { Component, Input } from '@angular/core'; @Component({ selector: 'app-upload-button', templateUrl: './upload-button.component.html' }) export class UploadButtonComponent { // 接收上层组件传入的文件输入框DOM元素 @Input() fileInput!: HTMLInputElement; triggerUpload() { this.fileInput?.click(); } }<button (click)="triggerUpload()">upload video</button> - 第二步:修改组件1的代码,拿到本地input引用后传给共享组件
组件1 ts文件:
组件1 模板文件:import { Component, ViewChild, ElementRef } from '@angular/core'; @Component({ selector: 'app-component1', templateUrl: './component1.component.html' }) export class Component1Component { // 拿到模板中#file对应的元素引用 @ViewChild('file') fileInput!: ElementRef<HTMLInputElement>; }<input type="file" accept=".mp4" #file /> <!-- 把input的原生DOM元素传给共享组件 --> <app-upload-button [fileInput]="fileInput.nativeElement"></app-upload-button>
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

