将变量传递给ng-container元素

时间:2019-01-14 13:39:12

标签: angular ionic3 angular5

我有一个带有重复html代码的开关盒,所以我想通过使用ng-container来减少这种情况,如下所示:

<div *ngSwitchCase="competences">
  <ng-container *ngTemplateOutlet="commonOsiCatalogInfoContainer"></ng-container>
</div>

这是ng-template:

<ng-template #commonOsiCatalogInfoContainer>
    <osi-catalog-info-container>
        <div header>
            {{ veld.titel }}
        </div>
        <div body>
            <li *ngFor="let blok of veld.waarde">
                <div class="s-margin-b">
                    <osi-li-h>{{ blok.toets_omschrijving }}</osi-li-h>
                </div>
                <ion-row *ngFor="let _veld of blok.velden" class="s-margin-b">
                    <ion-col col-auto class="work-form-title-col">
                        <osi-h4>{{_veld.titel}}</osi-h4>
                        <osi-li-body class="osi-black-87 d-block"><b>{{_veld.waarde}}</b></osi-li-body>
                    </ion-col>
                </ion-row>
            </li>
        </div>
    </osi-catalog-info-container>
</ng-template>

唯一不同的是在某些情况下osi-li-h的值是blok.title,如何才能在osi-li-h中使此ng-template动态?

2 个答案:

答案 0 :(得分:0)

您可以将上下文对象附加到ng-container并将值传递给模板。

根据docs

  

您可以通过设置[ngTemplateOutletContext]将上下文对象附加到EmbeddedViewRef。 [ngTemplateOutletContext]应该是一个对象,该对象的键将可用于由本地模板let声明进行绑定。

在模板内部,您必须执行以下操作:

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

答案 1 :(得分:0)

您可以像本文档中所述将上下文传递给ngTemplate https://angular.io/api/common/NgTemplateOutlet

您可以在两个方法之一中提供您的上下文

<div *ngSwitchCase="Field.FIELD_NAME_COMPETENCES">
  <ng-container *ngTemplateOutlet="commonOsiCatalogInfoContainer; context: contextExp"></ng-container>
</div>

或直接使用ngTemplate

<div *ngSwitchCase="Field.FIELD_NAME_COMPETENCES">
    <ng-template [ngTemplateOutlet]="commonOsiCatalogInfoContainer [ngTemplateOutletContext]="contextExp"></ng-template>
</div>
在以上两个示例中,

contextExp只是一个JSON对象。

然后,您可以直接在模板内部使用传递的上下文属性,例如

<ng-template #commonOsiCatalogInfoContainer let-myIdentifier="JSON_PROPERTY">
    <osi-catalog-info-container>

<div *ngIf="myIdentifier == 'something'"></div>

    </osi-catalog-info-container>
</ng-template>