Search This Blog

2023/09/03

create custom directive in angular

 we will see how to generate custom directive which is opposite of ngif,To generate new directive run following


ng generate directive Not

In not.directive.ts add following

import { Directive, Input, OnInit, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
selector: '[appNot]'
})
export class NotDirective implements OnInit {
constructor(private templateRef: TemplateRef<unknown>, private vcr: ViewContainerRef) {

}

@Input() appNot: boolean = false;

ngOnInit(): void {
if (this.appNot) {
this.vcr.createEmbeddedView(this.templateRef);
} else {
this.vcr.clear();
}
}

}

in app.module.ts import newly created directive as

import { NotDirective } from './not.directive'

Now include this declartion array below

To use it i created loginMessge variable in my signup.component.ts file,
on form submit the message from api response is populated in this variable

in signup.component.html file i am displaying this message as


<small *appNot="!loginMessge">
{{loginMessge}}
</small>


No comments:

Post a Comment