我有角度組件,我通過內容將一個組件投影到另一個組件中。例如:
app-component-a-controls投影到app-component-a. app-component-a繪制幾個app-component-a-controls通過*ngFor。
app-component-a HTML:
<app-component-a>
<app-component-a-controls>
<button (click)="log(record)">Click Me!</button>
</app-component-a-controls>
</app-component-a>
app-component-a-controls HTML:
<... *ngFor="...">
<ng-content select="app-component-a-controls"></ng-content>
</...>
我需要以某種方式訪問??外部的專案,例如當我單擊 button 時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>
任何想法,我怎樣才能實作它?
uj5u.com熱心網友回復:
您可以將您button的@Input()of<app-component-a-controls>作為 a傳遞TemplateRef。
所以你的應用程式組件模板看起來像這樣......
應用程式組件.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>
請注意我們宣告為模板變數的let-record="record"on ,ng-template當我們在app-component-a-controls組件中呈現模板時將決議該變數。
然后在您app-component-a-controls的模板中使用ng-containerwith渲染按鈕模板[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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/398052.html
