如何将上下文从 *ngIf 传递到 Angular 5 模板

How to pass context to Angular 5 template from *ngIf

Angular 的 NgTemplateOutlet 允许您将上下文传递到插座以进行 属性 绑定。

<ng-container *ngTemplateOutlet="eng; context: {$implicit: 'World'}"></ng-container>
<ng-template #eng let-name><span>Hello {{name}}!</span></ng-template>

Angular 的 *ngIf 允许您根据布尔条件嵌入一个或另一个模板:

<ng-container *ngIf="isConditionTrue; then one else two"></ng-container>
<ng-template #one>This shows when condition is true</ng-template>
<ng-template #two>This shows when condition is false</ng-template>

如何将上下文传递给 *ngIf 语法中引用的这些模板?

实际上你可以将你的条件输入到 ngTemplateOutlet 中(并去掉 ngIf)。

<ng-container *ngTemplateOutlet="condition ? template1 : template2; context: {$implicit: 'World'}">
</ng-container>

接受的答案在您只有一个表达式时有效,但在您有多个 ngIf 表达式和模板时会变得复杂。

具有多个表达式、结果模板甚至不同上下文变量的情况的完整示例:

<!-- Example ngFor -->
<mat-list-item
    *ngFor="let location of locations$; let l = index"
    [ngSwitch]="location.type"
    >
    <!-- ngSwitch could be ngIf on each node according to needs & readability -->

    <!-- Create ngTemplateOutlet foreach switch case, pass context -->
    <ng-container *ngSwitchCase="'input'">
        <ng-container 
            *ngTemplateOutlet="inputField; context: { location: location, placeholder: 'Irrigation Start', otherOptions: 'value123' }">
        </ng-contaier>
    </ng-container>

    <ng-container *ngSwitchCase="'select'">
        <ng-container 
            *ngTemplateOutlet="selectField; context: { location: location, selectSpecificOptions: 'scope.someSelectOptions' }">
        </ng-contaier>
    </ng-container>

    <!-- ngSwitchCase="'others'", etc. -->

</mat-list-item>



<!-- Shared ngTemplates & note let-[variable] to read context object into scope -->
<ng-template 
    #inputField 
    let-location="location"
    let-placeholder="placeholder
    let-otherOptions="otherOptions"
    <!-- Context is now accessible using let-[variable] -->
    INPUT: {{ location.value }} {{ placeholder }} {{ otherOptions }}
</ng-template>

<ng-template 
    #selectField 
    let-location="location"
    let-options="selectSpecificOptions"
    <!-- Context is now accessible using let-[variable] -->
    SELECT: {{ location.value }} {{ options }}
</ng-template>

哪里;

location$ = [
    {type: 'input',  value: 'test'}, 
    {type: 'input',  value: 'test 2'}, 
    {type: 'select', value: 'test 3'}
];