【问题标题】:Angular - Trigger function for each item inside loop individually in Angular 11Angular - 在 Angular 11 中单独为循环内的每个项目触发功能
【发布时间】:2021-08-04 22:27:57
【问题描述】:

我正在开发一个 Angular 项目,用户可以一次上传多个问题,添加问题后,列表以单独的模式显示,用户可以在其中为每个问题添加图表或图形问题。

因此,添加问题后,列表将在 question.component.html 文件中的 for 循环的帮助下显示。 [question-s2.component.html 是代表每个问题的组件。]

在下一个显示列表的Modal中,有一个“ADD DIAGRAM”选项,点击后会触发文件类型输入事件上传图片。一旦图像被选中,它应该调用函数“addDiagEvent”(在question-s2.component.ts中)

现在,这里的问题是当我只用一个问题尝试这个时(即,没有在 question.component.html 文件中引入循环),“addDiagEvent”函数被正确调用,其余功能是工作正常。

但如果有多个问题,则不会调用“addDiagramEvent”函数。我想为每个问题单独添加图表(图像)。

question.component.html 文件中: 这里,“uploadedSnips”是一个数组,包含所有问题,“questionUploaded”是 questions-s2.component 的一个属性,用于显示列表中的每个问题。

   <div class="questionModal-body">

      <app-question-s2 
        *ngFor="let question of uploadedSnips; let i = index"
        [questionUploaded]="question"
        [index]="i"
      >
      </app-question-s2>
      
   </div>

question-s2.component.html 文件中,我有这个标签“ADD DIAGRAM”来上传图片,它应该在 question-s2.component 中调用函数“addDiagEvent()” .ts 文件。

  <label mat-stroked-button for="uploadInput" class="outlineStyle-btn-diag">
    &#43; ADD DIAGRAM
  </label>
  <input id="uploadInput" type="file" style="display: none" (change)="addDiagEvent($event)"/>

<!-- diagram editor -->
  <ngx-photo-editor 
    [imageChanedEvent]="DiagAddEvent"
    (imageCropped)="croppedDiagMulti($event)"
  >
  </ngx-photo-editor>

  <img [src]="base64" alt="" />

question-s2.component.ts 文件中:

    // -------- ADD Diagram Events ---------------

      addDiagEvent(event: any): void {
        this.DiagAddEvent = event;
        console.log("Trigger editor");
      }

   // ------ After the photo has been cropped -------

      croppedDiagMulti(event: CroppedEvent): void {
        console.log("AfterCropped Func");
        this.diagMulti64 = event.file;
    
        const readerDiag = new FileReader();
        readerDiag.readAsDataURL(this.diagMulti64);
    
        readerDiag.onload = () => {
          this.diagMulti =
            typeof readerDiag.result === 'string' ? readerDiag.result : '';
          this.diagMulti64Url = this.diagMulti;
        };
      }

look at the UI 更好地理解:

编辑 另外,有没有办法根据 typeScript 中的索引使用动态变量名? 我想将 question-s2.component.ts 文件中的“diagMulti”变量更改为: diagMulti-0 表示第 0 个索引 第一个索引的 diagMulti-1 类似的东西?

【问题讨论】:

    标签: arrays reactjs angular typescript frontend


    【解决方案1】:

    一个可能的原因可能是输入标签的 id 在多个问题的情况下是静态的,因为标签标签无法对预期的输入标签应用操作。

    也许你可以试试这个。

    <label mat-stroked-button [attr.for]="'uploadInput-'+index" class="outlineStyle-btn-diag">
    &#43; ADD DIAGRAM</label>
    <input [id]="'uploadInput-'+index"  type="file" style="display: none" (change)="addDiagEvent($event)"/>
    

    【讨论】:

    • 为什么ID标签在角度上很重要? input 不会使用ngModel 来获取价值吗?
    猜你喜欢
    • 1970-01-01
    • 2021-04-19
    • 2019-10-10
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    相关资源
    最近更新 更多