Creating Custom Data Directives

Step 1: Build an Attribute Directive

Example: Auto-Format Text on Input

  1. Create the directive:
ng generate directive autoFormat
  1. Define its behavior:
// auto-format.directive.ts
@Directive({
 selector: '[appAutoFormat]'
})
export class AutoFormatDirective {
 @HostListener('input', ['$event']) onInput(event: Event) {
  const input = event.target as HTMLInputElement;
  input.value = input.value.toUpperCase();
 }
}
  1. Use it in a template:
<input appAutoFormat placeholder="Type in uppercase">

Step 2: Build a Structural Directive

Example: Delay Element Rendering

  1. Create the directive:
ng generate directive delayRender
2.define logic:
// delay-render.directive.ts  
@Directive({  
  selector: '[appDelayRender]'  
})  
export class DelayRenderDirective {  
  constructor(  
    private templateRef: TemplateRef<any>,  
    private viewContainer: ViewContainerRef  
  ) {}  

  @Input() set appDelayRender(delay: number) {  
    setTimeout(() => {  
      this.viewContainer.createEmbeddedView(this.templateRef);  
    }, delay);  
  }  
}  
3.use it in template:
<div *appDelayRender="2000">This content renders after 2 seconds.</div>  

Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu