我有以下组件用于渲染选项列表.optionsList
输入获取需要使用item
输入提供的自定义格式呈现的列表.
list-box.component.html
<div *ngFor="let option of optionsList; index as it">
<ng-container [ngTemplateOutlet]="item"></ng-container>
</div>
list-box.component.ts
@Component({
selector: 'app-list-box',
templateUrl: './list-box.component.html'
})
export class ListBoxComponent implements OnInit {
@Input('item') public item!:TemplateRef<any>;
@Input('optionsList') optionsList:any[]=[];
...
}
Then,在父组件中,我有一个模板,其中包含渲染每个项目的格式,并将其发送到任务的列表框组件:
In the parent.component.html
<ng-template let-option pTemplate="item" #item>
<label>{{it}}: {{option.name}}</label>
</ng-template>
<app-list-box
[optionsList]="[{'name': '...'}, ...]"
[item]="item">
</app-list-box>
这段代码显然不起作用,它显示了错误,即option
和it
在父级中不存在.
问题是,How can I send a particular format to render each item in the child component?.
我可以在子组件中使用特定格式,但如果项目列表具有其他类型的具有不同字段的项目,则列表框组件没有用处,我需要创建另一个特定组件或映射列表中的内容以设置所需字段的名称,但这不是所需的.
P.S.在本文中,我使用ngfor简化了代码,因为实际上这正是我所需要的.我不想把ngFor放在父对象中来设置那里的所有项,示例代码是我想要自定义的导入模块的模拟.