将自定义组件指令绑定到 for 循环中的对象

Bind custom component directive to object in for loop

我试图在视图中遍历我在组件 class 中用代码创建的组件列表,然后使用指令在 HTML 中显示该组件。

如何将指令绑定到列表中的组件实例:

这是我在代码中创建子组件列表的父组件:

import { Component, OnInit } from '@angular/core';
import { IFile } from '../Interfaces/IFile';
import { MatFileComponent } from './mat-file.component';

@Component({
  selector: 'mat-file-upload',
  templateUrl: './mat-file-upload.component.html',
  styleUrls: ['./mat-file-upload.component.css']
})
export class MatFileUploadComponent implements OnInit {
  constructor() { }
  fileList: IFile[]
  addFilesToList(files: File[]): void {
    this.fileList = [];
    for (let file of files) {
      let fileComponent = new MatFileComponent()
      fileComponent.fileData = file;
      fileComponent.fileDescription = 'this is my cool description';
      fileComponent.fileName = file.name;
      fileComponent.fileType = file.type;
      this.fileList.push(fileComponent);
    }
    console.log(this.fileList);
  }
  ngOnInit() {
  }
}

这是该组件的 html 模板,我在其中努力弄清楚如何绑定我的子组件的实际实例:

<input type="file" #file multiple id="singleFile" (change)="addFilesToList(file.files)" />
<div *ngIf="fileList && fileList.length">
  <mat-file *ngFor="let file of fileList" [howDoIBindThisTo]="file"></mat-file>
</div>

这是我的个人文件组件:

import { Component, OnInit } from '@angular/core';
import { IFile } from '../Interfaces/IFile';

@Component({
  selector: 'mat-file',
  templateUrl: './mat-file.component.html',
  styleUrls: ['./mat-file.component.css']
})
export class MatFileComponent implements OnInit, IFile {
  public fileName: string;
  public fileDescription: string;
  public fileData: File;
  public fileType: string;
  componentLoaded: boolean = false

  constructor() {}

  ngOnInit() {
    this.componentLoaded = true;
  }
}

这是对应的 HTML 模板:

<div *ngIf="componentLoaded">
  {{ fileType }} that's the type, here's the desc {{fileDescription}} and name {{fileName}}
</div>

您可以为组件创建四个输入参数

export class MatFileComponent implements OnInit, IFile {
  @Input() public fileName: string;
  @Input() public fileDescription: string;
  @Input() public fileData: File;
  @Input() public fileType: string;
  componentLoaded: boolean = false

  constructor() {}

  ngOnInit() {
    this.componentLoaded = true;
  }
}

现在绑定它使用:

<div *ngIf="fileList && fileList.length">
  <mat-file *ngFor="let file of fileList" 
     [fileName]="file.fileName"
     [fileDescription]="file.fileDescription"
     [fileData]="file.fileData"
     [fileType]="file.fileType"
  ></mat-file>
</div>