Angular 2 指令绑定

Angular 2 directive bind

我想在自定义指令中绑定 "ngFor" 索引作为属性 我做错了什么?

此代码:

@Directive({selector: '[closeWeb]'})
class CountClicks {
    numberOfClicks = 0;
    @HostListener('touchstart', ['$event.target'])
    touchstart(btn) {
        console.log(btn)
    }
}

@Component({
    selector: 'wrap',
    template: `
        <div class="wrap">
            <div class="item" *ngFor="#webviews of webviewsCount; #i = index">

                <!-- I want to bind index in custom directive as attribute -->
                <div [closeWeb]="i">{{i}}</div>

            </div>
        </div>
    `,
    directives: [CountClicks]
})

export class Wrap {}

我收到这个错误:

EXCEPTION: Template parse errors:
Can't bind to 'closeWeb' since it isn't a known native property ("</div><div [ERROR ->][closeWeb]="i">{{i}}</div></div></div>"): Wrap@9:21

只需将注释添加到指令中的 numberOfClicks 属性即可:

@Directive({selector: '[closeWeb]'})
class CountClicks {
  @Input('closeWeb')
  numberOfClicks = 0;

  (...)
}

这样您就可以将 numberOfClicks 属性定义为指令的输入参数,并能够在使用指令时获取您提供的值。

您可以查看 angular.io 文档:https://angular.io/docs/ts/latest/guide/attribute-directives.html。请参阅 "Configure the directive with binding".

部分

希望对你有帮助, 蒂埃里

import {Component,Directive,Input,HostListener} from 'angular2/core';

@Directive({selector: 'closeWeb'})
class CountClicks {
    @Input('closeWeb2')
    numberOfClicks = 0;
    @HostListener('click', ['$event.target'])
    touchstart(btn) {
        console.log('click = '+btn+' - '+this.numberOfClicks); 
    }
}

@Component({
    selector: 'wrap',
    template: `
        <div class="wrap">
            webviewsCount : {{webviewsCount | json}}<br/> 
            <div class="item" *ngFor="#webviews of webviewsCount; #i = index">

                <!-- I want to bind index in custom directive as attribute -->
                <div style="widhth:30px; height: 30px; border: solid 1px black"
                     ><closeWeb [closeWeb2]="i">{{i}}</closeWeb>{{i}}</div>

            </div>
        </div>
    `,
    directives: [CountClicks]
})

export class Wrap {
  constructor() {
    this.webviewsCount = [
      { value: 1 },
      { value: 2 },
      { value: 3 }
    ];
  }
}