使用 ng 内容将上下文传递给角度组件选择器



我有角度组件,我通过内容将一个组件投影到另一个组件中。例如:

app-component-a-controls被投射到app-component-a.app-component-a通过*ngFor绘制了几个app-component-a-controls

app-component-aHTML 文件:

<app-component-a>
<app-component-a-controls>
<button (click)="log(record)">Click Me!</button>
</app-component-a-controls>
</app-component-a>

app-component-a-controlsHTML 文件:

<... *ngFor="...">
<ng-content select="app-component-a-controls"></ng-content>
</...>

我需要以某种方式访问外面的项目,例如当我单击按钮Click Me!时,我需要获取 ngFor 相应的项目作为名为record的参数。如下所示:

<app-component-a>
<app-component-a-controls let-record>
<button (click)="log(record)">Click Me!</button>
</app-component-a-controls>
</app-component-a>

任何想法,我该如何实现?

您可以将button作为TemplateRef通过<app-component-a-controls>@Input()

所以你的应用程序组件模板看起来像这样。

app.component.html

<app-component-a>
<app-component-a-controls [buttonTemplate]="buttonTemplateExample"></app-component-a-controls>
<ng-template let-record="record" #buttonTemplateExample>
<button (click)="log(record)">Click Me!</button>
</ng-template>
</app-component-a>

请注意ng-template上的let-record="record",我们将它声明为模板变量,当我们在app-component-a-controls组件中呈现模板时,该变量将被解析。

然后在您的app-component-a-controls模板中,使用ng-container[ngTemplateOutlet]渲染按钮模板,然后使用[ngTemplateOutletContext]将"记录"值传递给我们的模板......

app-component-a-controls.component.html

<div *ngFor="let control of controls">
{{ control.label }}
<ng-container 
[ngTemplateOutlet]="buttonTemplate"
[ngTemplateOutletContext]="{ record: control.record }">
</ng-container>
</div>

app-component-a-controls.component.ts

import { Component, Input, OnInit, TemplateRef } from '@angular/core';
@Component({
selector: 'app-component-a-controls',
templateUrl: './component-a-controls.component.html',
styleUrls: ['./component-a-controls.component.css'],
})
export class ComponentAControlsComponent implements OnInit {
@Input()
public buttonTemplate: TemplateRef<any>;
public controls: any[] = [
{
label: 'ControlA',
record: 'This is the value for Control A',
},
{
label: 'ControlB',
record: 'This is the value for Control B',
},
];
constructor() {}
ngOnInit() {}
}

我把这种方法的工作堆栈放在一起......

https://stackblitz.com/edit/angular-ivy-e3wjne

最新更新