Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple directive selectors - find which selector was used in template

I have two selectors dirA and dirNotA for my directive. The directive should proceed further based on the selector used. Is there any way to determine which selector was used within the directive?

I do not wish to have multiple directives nor a directive with parameters. I wish to have one directive with multiple selectors and to determine the course of action based on the selector used in the template.

Something like this

@Directive({
  selector: '[dirA], [dirNotA]`
})
class DirectiveA implement OnInit {
  ngOnInit() {
    // here we detected which selector was used
    if (dirASelector) {
      ...
    }

  }
}

Any ideas how can get this information in the directive itself?

like image 908
s-f Avatar asked Oct 30 '25 04:10

s-f


1 Answers

You can use inheritance.

class DirectiveAOrNotA implements OnInit {
// common logic here
}

@Directive({
  selector: '[dirA]'
})
export class DirectiveA extends DirectiveAOrNotA {
// differences here
}

@Directive({
  selector: '[dirNotA]'
})
export class DirectiveNotA extends DirectiveAOrNotA {
// differences here
}

like image 82
mbojko Avatar answered Nov 01 '25 19:11

mbojko