Привязать директиву пользовательского компонента к объекту в цикле for - PullRequest
1 голос
/ 15 июня 2019

Я пытаюсь перебрать список компонентов, которые я создаю в коде в моем классе компонентов в моем представлении, и затем использовать директиву для отображения этого компонента в 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>

1 Ответ

1 голос
/ 15 июня 2019

Вы можете создать четыре входных параметра для вашего компонента

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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...