Binding events when using a ngForTemplate in Angular 2

前端 未结 2 1376
感情败类
感情败类 2020-12-01 09:33

Let\'s say I\'ve got this simple list rendering component:

import {Input, Component } from \'angular2/core\'

@Component({
  selector: \'my-list\',
  templat         


        
2条回答
  •  心在旅途
    2020-12-01 10:14

    Item template is defined in App context, it is not clear how to attach it to my-list component context. I have create wrapper directive that handles template and its variables, directive is wrapped into div to capture events. It can be used like this:

    @Directive({
        selector: '[ngWrapper]'
    })
    export class NgWrapper
    {
        @Input()
        private item:any;
    
        private _viewContainer:ViewContainerRef;
    
        constructor(_viewContainer:ViewContainerRef)
        {
            this._viewContainer = _viewContainer;
        }
    
        @Input()
        public set ngWrapper(templateRef:TemplateRef)
        {
            var embeddedViewRef = this._viewContainer.createEmbeddedView(templateRef);
            embeddedViewRef.setLocal('item', this.item)
        }
    }
    
    @Component({
      selector: 'my-list',
      directives: [NgWrapper],
      template: `
          
      `
    })
    class MyList {
        @Input() items: string[];
        @ContentChild(TemplateRef) userItemTemplate: TemplateRef;
        userItemTemplate1: TemplateRef;
    
        onItemClicked(item) {
            console.log('Item click:', item);
        }
    
        ngAfterViewInit(){
          this.userItemTemplate;
        }
    }
    
    @Component({
      selector: 'my-app',
      directives: [MyList],
      template: `
        
          
        
      `
    })
    export class App {
      items = ['this','is','a','test']
    
          onItemClicked(item) {
            console.log('Item click:', item);
        }
    }
    

    The solution is not prerfect but nearly good, check plunkr.

提交回复
热议问题