Skip to content

Instantly share code, notes, and snippets.

@cmjio
Created June 14, 2023 09:13
Show Gist options
  • Select an option

  • Save cmjio/edc21926a8a75667c9c2c7e0d3378371 to your computer and use it in GitHub Desktop.

Select an option

Save cmjio/edc21926a8a75667c9c2c7e0d3378371 to your computer and use it in GitHub Desktop.
@Directive({
selector: '[testId]'
})
export class TestIdDirective implements OnInit, OnDestroy {
private isTestIdEnabled: boolean = environment.production === false;
constructor(private el: ElementRef) { }
ngOnInit() {
if (this.isTestIdEnabled) {
const testId = this.el.nativeElement.getAttribute('testId');
if (testId) {
this.el.nativeElement.setAttribute('data-testid', testId);
}
}
}
ngOnDestroy() {
if (this.isTestIdEnabled) {
const testId = this.el.nativeElement.getAttribute('testId');
if (testId) {
this.el.nativeElement.removeAttribute('data-testid');
}
}
}
}
// usage
<button testId="submit-button">Submit</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment