代码之家  ›  专栏  ›  技术社区  ›  BeetleJuice

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

  •  20
  • BeetleJuice  · 技术社区  · 8 年前

    角度的 NgTemplateOutlet 允许您将上下文传递到用于属性绑定的出口。

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

    角度的 *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公司 语法?

    2 回复  |  直到 8 年前
        1
  •  26
  •   Sielu    8 年前

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

    <ng-container *ngTemplateOutlet="condition ? template1 : template2; context: {$implicit: 'World'}">
    </ng-container>
    
        2
  •  4
  •   Ralpharoo    6 年前

    当您只有一个表达式时,可接受的答案有效,但当您有多个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'}
    ];