首页 文章

Angular - ng-template,其中ngIf内的参数在ngFor [duplicate]内

提问于
浏览
15

这个问题在这里已有答案:

我正在尝试构建此模板:

<ul>
    <li *ngFor='let link of links'>
        <ng-container *ngIf="link.type == 'complex'; then complexLink else simpleLink"></ng-container>
    </li>
</ul>

<ng-template #simpleLink>
    ...
    {{ link.some_property }}
</ng-template>

<ng-template #complexLink>
    ...
    {{ link.some_property }}
</ng-template>

问题是在ng-template中未定义链接变量,因此我得到访问未定义的'some_property'的错误 .

我很想知道如何将链接变量从ngFor传递到ng-template

很高兴知道这个问题是否有多种解决方案 .

2 回答

  • 39

    你可以这样做:

    <ul>
        <li *ngFor='let link of links'>
            <ng-container 
                 [ngTemplateOutlet]="link.type == 'complex' ?complexLink : simpleLink" 
                 [ngTemplateOutletContext]="{link:link}">
            </ng-container>
        </li>
    </ul>
    
    <ng-template #simpleLink let-link='link'>
        Simple : {{ link.name }}
    </ng-template>
    
    <ng-template #complexLink let-link='link'>
        Complex : {{ link.name }}
    </ng-template>
    

    WORKING DEMO

  • -1

    你可以这样使用它

    <ul>
      <li *ngFor='let link of links'>
          <ng-container *ngIf="link.type == 'complex'; then complexLink else simpleLink"></ng-container>
    
          <ng-template #simpleLink>
              ... {{ link.some_property }}
          </ng-template>
    
          <ng-template #complexLink>
              ... {{ link.some_property }}
          </ng-template>
      </li>
    </ul>
    

相关问题