父组件中的多个子组件具有相同的实例angular2

时间:2017-07-04 07:29:55

标签: javascript angular angular-components

我有一个子组件file-upload,我在父组件中多次使用,如下所示

<form>
<fieldset>
    <legend>Input Files</legend>

    <file-upload id="s" imgpath="Image/saham.png" title="saham"></file-upload>
    <file-upload id="q" imgpath="Image/sandoq.png" title="sandoq"></file-upload>
    <file-upload id="o" imgpath="Image/oraq.png" title="oraq"></file-upload>

    <button type="submit" class="btn btn-success" (click)="save()" [disabled]="!cansave">Save</button>
</fieldset>

在UI中

一切都很好,但在行动中似乎只有一个file-upload的对象实例正在工作,每个file-upload组件中的每个输入更改仅适用于其中一个(第一个)。

问题出在input以及我使用它的方式..当我使用一个简单的按钮时,一切都很好。这是file-upload

的html
    <div class="upload" (dragover)="allowDrop($event)" (drop)="drop($event)">
    <p>{{title}}</p>
    <div class="drop-zone" [ngClass]="{'showdropzone' : showdropzone}">
        Drop Here Or...
        <div class="clickhere">
            <label for="files">Click Here</label>
            <input id="files" type="file" class="file" (change)="fileSelect($event)"><!--does not work-->
            <button (click)="fileSelect($event)">Click Me</button> <!--this is working-->
        </div>
    </div>
    <circle-progress class="myprogress" #circleProg1 [percent]="50" [ngClass]="{'showprogress' : showprogress}"></circle-progress>
    <span class="glyphicon glyphicon-warning-sign status"  [ngClass]="{'warninput' : haswarning}"></span>
    <span class="glyphicon glyphicon-ok-circle status"     [ngClass]="{'successinput' : succeeded}"></span>
</div>

1 个答案:

答案 0 :(得分:1)

您有一个 singleton FileService,这就是为什么他们都拥有该服务的相同实例的原因。我假设您在AppModule中注入了提供程序,因此请将其删除并尝试在组件级别注入您的服务

@Component){
  providers: [FileService]
  ...
}
export class FileUploadComponent

有关多个服务实例的详细信息,请查看此from official docs。 希望这有帮助