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

时间:2018-02-15 15:15:20

标签: angular templates if-statement angular-template

Angular'} NgTemplateOutlet允许您将上下文传递到出口以进行属性绑定。

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

Angular&#39; *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语法中提到的这些模板?

3 个答案:

答案 0 :(得分:7)

实际上,您可以将条件输入到ngTemplateOutlet中(并摆脱ngIf)。

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

答案 1 :(得分:1)

当您只有一个表达式时,可接受的答案会起作用,但是如果您有多个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'}
]; 

答案 2 :(得分:-3)

为什么不这样做:

<ng-container *ngIf="isConditionTrue; else two">
 // your first template, #one, goes here.
</ng-container>

<ng-template #two>
 // your second template, #two goes here.
</ng-template>