1

我试图在我的视图中循环访问我在组件类中的代码中创建的组件列表,然后使用指令在 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>
4

1 回答 1

1

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

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>
于 2019-06-15T18:31:05.960 回答