我试图遍历我在视图中的组件类中的代码中创建的组件列表,然后使用指令在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>
答案 0 :(得分: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>