I have created a custom directive in my angular project. I want to use it to a DOM element in typescript. how to do that if it's possible? thank you!
I didn't find anything useful in my searches
I have created a custom directive in my angular project. I want to use it to a DOM element in typescript. how to do that if it's possible? thank you!
I didn't find anything useful in my searches
I think you're looking about how to make a custom directive & use to any HTML element to manipulate the tag also,
Here is some code snippet I hope it will help you to understand, Its a alternative way to make *ngIf
so far this is the basic structure of making custom directive you can take Idea from it & extend it more further. By the way this directive also type-safe.
import {Directive, Input, TemplateRef, ViewContainerRef} from '@angular/core';
class IfContext {
public isShow: boolean = true;
public get $implicit() {
return this.isShow;
}
}
@Directive({
selector: '[appIf]',
standalone: true
})
export class IfDirective {
public ifContext = new IfContext()
constructor(
private viewContainerRef: ViewContainerRef,
private templateRef: TemplateRef<any>
) {
}
@Input('appIf') set setIf(value: boolean) {
this.ifContext.isShow = value;
if (value) {
this.viewContainerRef.clear();
} else {
this.viewContainerRef.createEmbeddedView(this.templateRef)
}
}
static ngTemplateContextGuard(dir: IfDirective, ctx: unknown): ctx is IfContext {
return true
}
}
so, in the component you can use it like bellow & if you not provide any boolean value it will throw error.
<h2 *appIf="show">Hello World</h2>
Thanks
I would recommend you declare your directive in a shared module and export the directive to use it over the complete project you create. like this:
@NgModule({
declarations: [customDirective],
exports:[customDirective]
})
export class SharedModule { }