0

我想将自定义指令中的“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
4

2 回答 2

2

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

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

  (...)
}

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

您可以查看 angular.io 文档:https ://angular.io/docs/ts/latest/guide/attribute-directives.html 。请参阅“使用绑定配置指令”部分。

希望它可以帮助你,蒂埃里

于 2016-01-14T13:09:58.890 回答
0
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 }
    ];
  }
} 
于 2016-12-06T09:30:38.037 回答