我想实现一个称为“上传文件”的指令,该指令将应用于<button>
元素。它的用法是:
<button upload-file> Upload a file </button>
该指令应添加一个隐藏的<input>
,单击该按钮时,该指令代码将单击<input>
元素。最终的DOM为:
<button upload-file>Upload a file</button>
<input type="file" #uploaderInputEl ng2FileSelect [uploader]="uploader" />
我尝试通过Renderer2创建<input>
元素:
private appendInputElement = () => {
this.inputElement = this._renderer.createElement('input');
this._renderer.setAttribute(this.inputElement, "type", "file");
this._renderer.setStyle(this.inputElement, "width", "0");
this._renderer.setStyle(this.inputElement, "visibility", "hidden");
this._renderer.setAttribute(this.inputElement, "accept", this.acceptedFileExtensions);
this._renderer.listen(this.inputElement, "change", (event) => this.inputElement_change(event));
// set directive: ng2FileSelect
// set property binding: [uploader]="uploader"
this._renderer.appendChild(this.containerElement, this.inputElement);
}
但是我不知道如何设置directive
(ng2FileSelect)和property binding
([uploader] =“ uploader”)。我知道它们是“角度功能”,与我使用_renderer.listen()
设置的“事件绑定”(更改)相同。
是否可以设置指令和属性绑定?
不幸的是,Angular没有提供从代码动态设置指令的方法