【问题标题】:Bind custom component directive to object in for loop将自定义组件指令绑定到 for 循环中的对象
【发布时间】:2019-10-29 23:18:00
【问题描述】:

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

【问题讨论】:

    标签: angular angular-directive angular-components property-binding


    【解决方案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>
    

    【讨论】:

      猜你喜欢
      • 2017-07-09
      • 2014-12-19
      • 2014-08-11
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 2016-11-02
      相关资源
      最近更新 更多