0

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

验证码:

@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>"): [email protected]:21 

回答

2

简单的注释添加到您的numberOfClicks属性在你的指令:

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

    (...) 
} 

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

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

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

+0

不幸的是,它并不能帮到我。然后我添加注释,错误消失,但然后我点击元素,我只有标签没有指令'

0
'。我想获得'
0
' –

+0

实际上,该指令实际上是应用的。我的意思是你可以点击几次元素。看到这个plunkr:https://plnkr.co/edit/Lm4qnfcAhmTDXpELh6ib?p=preview。为什么你需要'closeweb'zttribute仍然存在? –

+0

工作,非常感谢!这个索引作为属性需要我在业务逻辑中的其他功能(我将代码从Angular 1.4升级到Angular 2)。但是我有一个问题,那么你在这段代码中替换'touchstart'到'c​​lick'' @HostListener('touchstart',['$ event.target']); touchstart(btn){console.log('click ='+ btn +' - '+ this.numberOfClicks); }' - 你实现click作为touchstart事件,对吧? –

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 } 
    ]; 
    } 
} 
+0

这个答案增加了没有价值的问题。问题已经接受了答案,你完全没有解释。 – rzelek