2

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?

3
  • 4
    From my understanding, you want to add dynamic event listener to the div refer to this stackoverflow.com/questions/35080387.. Commented Jun 2, 2016 at 4: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. Commented Jun 4, 2016 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.'<div id="'+varID+'"></div>' in jquery, if it is proper here. Commented Jun 4, 2016 at 13:48

1 Answer 1

3

You can't do that.

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

Sign up to request clarification or add additional context in comments.

1 Comment

A static or read only property on the class should be statically analyzable, no? I want to avoid magic strings and have the ability to provide extra documentation through doc comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.