Pass variable in Angular 2 template

前端 未结 4 1609
情书的邮戳
情书的邮戳 2020-12-09 04:47

Is there a way I can pass variables to templates in Angular2?

Let\'s say I have the following code:

相关标签:
4条回答
  • 2020-12-09 05:02

    You should do like this:

    <div *ngFor="foo in foos">
       <ng-container *ngTemplateOutlet="inner; context:foo"></ng-container>
    </div>
    
    <ng-template #inner let-name="name">
       {{ name }}
    </ng-template>
    
    0 讨论(0)
  • 2020-12-09 05:05

    But this doesn't work if the template is located in another component. How do you pass a context object in such scenario?

    I added
    @Input() itemTemplate: TemplateRef<any>;

    in component where I will use it, and in template of this component I write something like this:

      <ng-container *ngTemplateOutlet="itemTemplate; context: item"></ng-container>
    

    Code of template from outside component:

    <ng-template #dataRendererTpl let-data="data">
    <div class="data">Hello, {{data.name}}</div>
    

    Just pass link to dataRendererTpl as @Input() property to component in which you need it

    0 讨论(0)
  • 2020-12-09 05:14

    in my case I needed the object to remain intact because I had some kind of recursion, this worked

    <div *ngFor="foo in foos">
       <ng-container *ngTemplateOutlet="inner; context: {foo : foo}"></ng-container>
    </div>
    
    <ng-template #inner let-foo="foo">
       {{ foo.attributexy }}
    </ng-template>
    
    0 讨论(0)
  • 2020-12-09 05:19

    In the case you want to send the whole iterable object to the template, you can pass the array into the context as follow:

    <ng-container *ngTemplateOutlet="inner; context:foos"></ng-container>
    
    <ng-template #inner let-foos="values()">
       <div *ngFor="foo in foos">
          {{ foo.name }}
       </div>
    </ng-template>
    
    0 讨论(0)
提交回复
热议问题