Can't get ngTemplateOutlet to work

前端 未结 3 1996
我寻月下人不归
我寻月下人不归 2020-12-03 07:06

I am trying to build a listing component in Angular2 that takes the items, the columns and the templates for the fields of the items from the user of the component. So I am

相关标签:
3条回答
  • 2020-12-03 07:33

    This is how you need to do this:

    @Component({
      selector: 'my-component',
      template: `
        <div *ngFor="let item of items">
          <span *ngFor="let column of columns">
            <template [ngTemplateOutlet]="column.ref" [ngOutletContext]="{ item: item }"></template>
          </span>
        </div>`
    })
    export class MyComponent {
      @Input() items: any[];
      @Input() columns: any[];
    }
    
    @Component({
      selector: 'my-app',
      template: `
        <div>
          <my-component [items]="cars" [columns]="columns">
            <template #model let-item="item">{{item?.model}}</template>
            <template #color let-item="item">{{item?.color}}</template>
          </my-component>
        </div>`
    })
    export class App {
      @ViewChild('model') model;
      @ViewChild('color') color;
      cars = [
          { model: "volvo", color: "blue" },
          { model: "saab", color: "yellow" },
          { model: "ford", color: "green" },
          { model: "vw", color: "orange" }
        ];
    
      ngAfterContentInit() {
        this.columns = [
          { ref: this.model },
          { ref: this.color ]
        ];
      }
    }
    

    Plunker

    0 讨论(0)
  • 2020-12-03 07:43

    you can do it without ngOutletContext. You have to use ng-template instead of template. following code works for me:

    app.component.html:

    <div>
      <ng-template #c1>
        <app-child1></app-child1>
      </ng-template>
      <app-parent [templateChild1]="c1"></app-parent>
    </div>
    

    app-parent is a child of app-component. app-child is declared in app-component as template and this template is used in app-parent.

    app.parent.html:

    <p>
      <ng-template [ngTemplateOutlet]="templateChild1"></ng-template>
    </p>
    

    app.parent.ts:

    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
      styleUrls: ['./parent.component.css']
    })
    export class ParentComponent implements OnInit {
    
      @Input() public templateChild1: TemplateRef<any>;
    
      public ngOnInit() {
      }
    
    }
    
    0 讨论(0)
  • 2020-12-03 07:52

    update Angular 5

    ngOutletContext was renamed to ngTemplateOutletContext

    See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

    original

    Don't use [] and {{}} together. Either the one or the other but not both.

    Don't use {{}} if you want to pass an object because {{}} is for string interpolation.

    It should be

    [ngTemplateOutlet]="column.templateRef"
    

    Plunker example

    0 讨论(0)
提交回复
热议问题