3

I have the following attribute directive

import { Directive,HostListener,Input } from '@angular/core';

@Directive({
  selector: `[appConfirmaction]`
})
export class ConfirmactionDirective {
  @Input() appConfirmaction = () => {};
  @Input() confirmMessage = 'Do you want to keep going?';

  @HostListener('click', ['$event'])
  confirmFirst() {
    const confirmed = window.confirm(this.confirmMessage);

    if(confirmed) {
      this.appConfirmaction();
    }
  }
}

Then I'm using the above directive attribute in a button, such as

<button md-icon-button [appConfirmaction]="showSimpleMessage" >

The code of the function of the component is:

showSimpleMessage(){
    alert("Hello");
  }

This code works perfectly.

Now, suppose that I want to add a parameter to the function showSimpleMessage, such as

showSimpleMessage(name:string){
    alert("Hello "+name);
  }

What are the changes that I have to do to the attribute directive to support the new parameter without using a new @Input for the name parameter? Also, Is this the proper way to call a function from an attribute directive with Angular4?

Cheers.

2 Answers 2

4

Use bind

  <button  [appConfirmaction]="showSimpleMessage.bind(null, 'Julia')" >
       click me 
  </button>
Sign up to request clarification or add additional context in comments.

Comments

0

You wouldn't have to change much. Just put argument to your calling of showSimpleMessage function in directive:

if(confirmed) {
  this.appConfirmaction('some name');
}

If this doesn't work correctly you can use call() method on that function. This solution is if you want to call it from directive:

if(confirmed) {
  this.appConfirmaction.call(null, 'some name');
}

First argument null is actually context this that you can provide to the function. 'some name' is the parameter of the function.

The other solution is to use bind() as suggested by @Julia

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.