programing

ngIf inside ngFor 매개변수가 있는 Angular - ng-template

starjava 2023. 5. 22. 20:05
반응형

ngIf inside ngFor 매개변수가 있는 Angular - ng-template

이 템플릿을 작성하려고 합니다.

<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로 전달하는 방법을 이해하려고 노력하고 있습니다.

이 문제에 대한 여러 가지 해결책이 있는지 알면 좋을 것 같습니다.

다음과 같이 할 수 있습니다.

<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>

작업 데모

이런 식으로 사용할 수 있습니다.

<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>

언급URL : https://stackoverflow.com/questions/48515267/angular-ng-template-with-parameter-inside-ngif-inside-ngfor

반응형