简体   繁体   中英

angular2 ng-container how to use dynamic ngTemplateOutletContext

I'm trying to use ng-container with NgTemplateOutlet ( https://angular.io/docs/ts/latest/api/common/index/NgTemplateOutlet-directive.html )

      <div *ngFor="let child of children; let i=index">
      <ng-container *ngTemplateOutlet="inputTpl; { $implicit: child, index: i }"></ng-container>
  </div>

Thie results in the error

Unexpected token {, expected identifier, keyword, or string at column 11 in [inputTpl; { $implicit: child, index: i }]

When I use 'context:' like in the docs, this leads to

Can't bind to 'ngTemplateOutletContext' since it isn't a known property of 'ng-container'

If I use a object declared in my ts file and set it instead of my Object, everything is working fine. Moreover this is also working fine:

      <div *ngFor="let child of children; let i=index" class="form-group">
      <template [ngTemplateOutlet]="inputTpl" [ngOutletContext]="{ $implicit: child, index: i }" />
    </div>

Does anybody know, how I can use ng-container with *ngTemplateOutlet and ngTemplateOutletContext generated in the html?

Did you try <ng-container> with [ngTemplateOutletContext] like this?

<ng-container
    [ngTemplateOutlet]="inputTpl"
    [ngTemplateOutletContext]="{ $implicit: child, index: i }"
>
</ng-container>

Example for angular 5.

<ng-container  [ngTemplateOutlet]="optionTemplate.template" [ngTemplateOutletContext]="{option:option}">
</ng-container>


<p-auto-complete property='searchText' [options]="options"(onChange)="select($event)">
        <ng-template pOptionTemplate  let-option="option">
            <div>
              //...
            </div> 
        </ng-template>
 </p-auto-complete>

stackblitz

Maybe you should update your dependencies to 2.4?

  "dependencies": {
    "@angular/common": "~2.4.3",
    "@angular/compiler": "~2.4.3",
    "@angular/core": "~2.4.3",
    "@angular/forms": "~2.4.3",
    "@angular/http": "~2.4.3",
    "@angular/platform-browser": "~2.4.3",
    "@angular/platform-browser-dynamic": "~2.4.3",
    "@angular/platform-server": "~2.4.3",
    "@angular/router": "~3.4.3",
    "@angularclass/conventions-loader": "^1.0.2",
    "@angularclass/hmr": "~1.2.2",
    "@angularclass/hmr-loader": "~3.0.2",
    "core-js": "^2.4.1",
    "http-server": "^0.9.0",
    "ie-shim": "^0.1.0",
    "jasmine-core": "^2.5.2",
    "reflect-metadata": "^0.1.9",
    "rxjs": "~5.0.2",
    "zone.js": "~0.7.4"
  },

call to the main template

<ng-template *ngTemplateOutlet="callMain; context: { $implicit: item }"></ng-template> // can use multiple places

main template

<ng-template #callMain let-item>
  //use dynamic item object
</ng-template>

您可能必须在声明当前组件的模块中导入CommonModule

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM