我有以下组件用于渲染选项列表.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>

这段代码显然不起作用,它显示了错误,即optionit在父级中不存在.

问题是,How can I send a particular format to render each item in the child component?.

我可以在子组件中使用特定格式,但如果项目列表具有其他类型的具有不同字段的项目,则列表框组件没有用处,我需要创建另一个特定组件或映射列表中的内容以设置所需字段的名称,但这不是所需的.

P.S.在本文中,我使用ngfor简化了代码,因为实际上这正是我所需要的.我不想把ngFor放在父对象中来设置那里的所有项,示例代码是我想要自定义的导入模块的模拟.

推荐答案

考虑以下代码:

父.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>
  1. ✓ 我可以看到参数let-option是隐式的,这是因为它没有被分配给上下文的特定元素.(示例:let example="something")[有效]

  2. ???? 变量"it"尚未定义,这可能会产生错误.[无效]


考虑到{it}}表示回路的当前位置,可以按以下方式进行:

父.component.html:

<ng-template let-option let-it="index" #item>
  <label>{{it}}: {{option.name}}</label>
</ng-template>

<app-list-box
  [optionsList]="[{'name': '...'}, ...]"
  [item]="item">
</app-list-box>

列表框.component.html:

<div *ngFor="let option of optionsList; let i = index">
  <ng-container *ngTemplateOutlet="item; context: {$implicit: option, index: i}"></ng-container>
</div>

需要注意的是:

$implicit->;将被分配到let-option

测试演示:https://codesandbox.io/s/elegant-sea-diiu5x

Angular相关问答推荐

有没有一种方法用timeout()操作符创建计数器,用于超时一个观察对象?

如何使用新的@for遍历Angular 为17的对象?

独立Angular 零部件不在辅零部件或共享零部件中工作

天使17中的倒计时器

如何将 Firebase 云消息传递 (FCM) 与 Angular 15 结合使用?

如何在 Angular RxJS 中替换订阅中的 subscrib?

如何在 Angular 库中将依赖项声明为可选?

nx workspace angular monorepo 在创建新应用程序时抛出错误

错误:在@angular/core中找不到导出ɵivyEnabled(导入为ɵivyEnabled)

BehaviorSubject 在 Angular 中制作数据之间的时间表(或计时器)

Angular 项目构建仅在 GitHub Actions 上失败

Angular:将间隔与增量和减量相结合

绑定 Angular material Select 列表

如何以像素为单位将属性绑定到 style.width?

如何停止在 ngOnInit() 之前调用的 ngOnChanges

Angular 5 手动导入语言环境

Angular Material 模态对话框周围的空白

NG 测试中的调试测试

Angular 2 Material 2 日期 Select 器日期格式

Angular4中ActivatedRoute和ActivatedRouteSnapshot有什么区别