Pas*_*ten 62 file-upload input angular
使用角度2 beta,我似乎<input type="file">无法上班.
使用诊断,我可以看到其他type的双向绑定,如text.
<form>
{{diagnostic}}
<div class="form-group">
<label for="fileupload">Upload</label>
<input type="file" class="form-control" [(ngModel)]="model.fileupload">
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
在我的TypeScript文件中,我有以下诊断线:
get diagnostic() { return JSON.stringify(this.model); }
Run Code Online (Sandbox Code Playgroud)
可能是因为它不是JSON的问题吗?价值是null.
我无法真正验证它的价值input.У尽管"选择文件..."旁边的文字更新了,但由于某种原因,我无法看到DOM的差异.
Thi*_*ier 67
我认为它不受支持.如果你看一下这个DefaultValueAccessor指令(参见https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/directives/default_value_accessor.ts#L23).您将看到用于更新绑定元素的值是$event.target.value.
这不适用于具有类型的输入,file因为可以到达文件对象$event.srcElement.files.
有关详细信息,您可以查看此plunkr:https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg ? p = info :
@Component({
selector: 'my-app',
template: `
<div>
<input type="file" (change)="onChange($event)"/>
</div>
`,
providers: [ UploadService ]
})
export class AppComponent {
onChange(event) {
var files = event.srcElement.files;
console.log(files);
}
}
Run Code Online (Sandbox Code Playgroud)
Ash*_*iya 40
@Component({
selector: 'my-app',
template: `
<div>
<input name="file" type="file" (change)="onChange($event)"/>
</div>
`,
providers: [ UploadService ]
})
export class AppComponent {
file: File;
onChange(event: EventTarget) {
let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
let files: FileList = target.files;
this.file = files[0];
console.log(this.file);
}
doAnythingWithFile() {
}
}
Run Code Online (Sandbox Code Playgroud)
Fre*_*ren 30
有一种更好的方式来访问附加文件.您可以使用模板引用变量来获取input元素的实例.
以下是基于第一个答案的示例:
@Component({
selector: 'my-app',
template: `
<div>
<input type="file" #file (change)="onChange(file.files)"/>
</div>
`,
providers: [ UploadService ]
})
export class AppComponent {
onChange(files) {
console.log(files);
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个示例应用程序,用于演示此操作.
模板引用变量可能很有用,例如,您可以直接在控制器中通过@ViewChild访问它们.
另一种使用模板引用变量和ViewChild的方法,如Frelseren所提出的:
import { ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div>
<input type="file" #fileInput/>
</div>
`
})
export class AppComponent {
@ViewChild("fileInput") fileInputVariable: any;
randomMethod() {
const files = this.fileInputVariable.nativeElement.files;
console.log(files);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
128828 次 |
| 最近记录: |