1

I have simple click event binding

@Component({template:` <div ({{eventStr}})="do-log()">DoLog</div>`})
export class AppComponent {
    eventStr:string="click";
    do-log(){
        console.log("ckp");
    }
}

of course it will work if change ({{eventStr}}) to (click) .I try many way like (${eventStr}) ,(eventStr). I don't understand ,inside (click)="do-log()" ,this click is not string or what other type? I want to use eventStr instead of click because I want to change event type dynamic,e.g. swipe.

Update: I know there are two way @HostBinding and renderer.listen, but I have different use case and find some way like this: in parent component template like:

 <child-cmp eventType="swipe">Swipe</child-cmp><child-cmp eventType="click">Click</child-cmp>

and in child component template like:

<div><button (eventType)="dosomething_accordingTo_diff_touch_events()"></button></div>

of course with @Input eventType:string. It doesn't work. I guess if eventType is not a string but an event object, in fact (eventType)==("swipe") or==("click"), not equal to (swipe) or (click). so is there one way to let (eventType)==(swipe) inside template?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
PengGang
  • 15
  • 5
  • 4
    From my understanding, you want to add dynamic event listener to the `div` refer to this http://stackoverflow.com/questions/35080387.. – Madhu Jun 02 '16 at 04:02
  • 1
    In event bindings `(eventname)="dosomething"` `(eventname)` has to be static text in the template. You can't read it from some input or set it dynamically in any way like explained in the comment above or the answer below. You have to do it imperatively like explained in the links already provided. – Günter Zöchbauer Jun 04 '16 at 10:17
  • Understanding Madhu and drewmoore's explaining, and thank all of you. but I still hope someone can explain how angular template work and why we can have dynamic some variable inside html e.g.'
    ' in jquery, if it is proper here.
    – PengGang Jun 04 '16 at 13:48

1 Answers1

2

You can't do that.

Binding expressions have to be statically analyzable, so you cannot generate them dynamically. Same goes for anchors (discussion here).

drew moore
  • 31,565
  • 17
  • 75
  • 112