How to include a file upload control in an Angular2 reactive form?

前端 未结 3 904
有刺的猬
有刺的猬 2020-12-08 14:42

For some weird reason, there are just no tutorials or code samples online showing how to use Angular2 Reactive forms with anything more than simple input or select dropdowns

3条回答
  •  长情又很酷
    2020-12-08 15:05

    I'm a bit late to this, but for anyone else that may come here looking for the same solution - This is my file input accessor that can be used with Reactive or Template-driven forms. Demo here.

    There's some optional validation provided with it that can be used to check image dimensions and file size, extension, type, which is disabled by default.

    npm i file-input-accessor and add the module to your AppModule imports:

    import {BrowserModule} from '@angular/platform-browser';
    import {FileInputAccessorModule} from "file-input-accessor";
    
    @NgModule({
        declarations: [
            AppComponent
        ],
        imports: [
            BrowserModule,
            FileInputAccessorModule
        ],
        providers: [],
        bootstrap: [AppComponent]
    })
    export class AppModule {}
    

    Then use your file input like any other input:

    
    
    
    
    
    
    

    You can subscribe to valueChanges property just like any other reactive control.

提交回复
热议问题