Home > Software design >  How to use ngIf to choose diffrent selector in html in an angular app
How to use ngIf to choose diffrent selector in html in an angular app

Time:08-18

I have a question about how to use ngIF in HTML code to choose different selector.

I show my code as follow:

in HTML Code:

<a  (click)=clickFunction() (keyup.Enter)=ke()>
  <div>
    content

  </div>
</a>

this is html is in a shared component,

I want to use this shared component into the other component with input parameter noClickAndKeyEnter=true |false

so in this case I should change html code as follow:

<a  (click)="noClickAndKeyEnter ? clickFunction(): ''" (keyup.Enter)="noClickAndKeyEnter ? ke() :''">
  <div>
    content

  </div>
</a>

My question is, is there also the easy way to resolve my question, that I do not write all place with noClickAndKeyEnter ? :

any solutions?

CodePudding user response:

There are multiple ways you can do this. The simplest could be:

 clickFunction(){
    if(this.noClickAndKeyEnter){
      // execute code here
    } else {
      // just return or whatever you want here
    }
 }

CodePudding user response:

You can use the callback pattern!

ts

conditionallyExecute(callback: Function, ...params) {
    if(this.noClickAndKeyEnter) {
        callback(params)
    }
}

html

<a  (click)="conditionallyExecute(clickFunction, 1, 2)" (keyup.Enter)="conditionallyExecute(ke)">
  <div>
    content

  </div>
</a>
  • Related