在Angular 8中,可以使用ng-template
和*ngFor
结合使用来解决问题。下面是一个具体的示例:
首先,创建一个名为items.component.ts
的组件文件,并在其中定义一个items
数组,用来存储要循环显示的项目:
import { Component } from '@angular/core';
@Component({
selector: 'app-items',
template: `
{{ item }}
`,
})
export class ItemsComponent {
items: string[] = ['Item 1', 'Item 2', 'Item 3'];
}
在items.component.html
中,使用ng-container
来包含*ngFor
循环和ng-template
模板,并使用let-item
来声明模板中的变量。在ng-template
中,可以根据需要定义要显示的内容。
在父组件的模板中,可以使用app-items
组件,并在其中使用ng-template
来定义具体要显示的内容:
{{ item }} - Custom Template
在上面的示例中,我们在app-items
组件中定义了一个名为itemTemplate
的模板,并在其中添加了自定义的内容。这个模板将替代items.component.ts
中定义的默认模板。
最后,将app-items
组件添加到父组件的模板中,即可实现根据需要自定义循环项的显示。
希望这个示例能帮助你解决Angular 8中的ng-template
和*ngFor
问题!