
Steps to create directive
Step 1 create an angular application with command
ng new directiveApp
Step 2 create an directive with command
ng generate directive directiveName
Step 3 copy and paste the code given in above directive.ts file.
directive.ts
import { Directive,ElementRef,Input,HostListener } from '@angular/core';
@Directive({
selector: '[appDirectives]'
})
export class DirectivesDirective {
inputElement: ElementRef;
@Input('appDirectives')
appDirectives!: string;
arabicRegex = '[\u0600-\u06FF]';
constructor(el: ElementRef) {
this.inputElement = el;
}
@HostListener('keypress', ['$event']) onKeyPress(event: any) {
this.notAllowSpaceatFirst(event)
}
integerOnly(event: any) {
const e = <KeyboardEvent>event;
if (e.key === 'Tab' || e.key === 'TAB') {
return;
}
if (['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'].indexOf(e.key) === -1) {
e.preventDefault();
}
}
noSpecialChars(event: any) {
const e = <KeyboardEvent>event;
if (e.key === 'Tab' || e.key === 'TAB') {
return;
}
let k;
k = event.keyCode; // k = event.charCode; (Both can be used)
if ((k > 64 && k < 91) || (k > 96 && k < 123) || k === 8 || k === 32 || (k >= 48 && k <= 57)) {
return;
}
const ch = String.fromCharCode(e.keyCode);
const regEx = new RegExp(this.arabicRegex);
if (regEx.test(ch)) {
return;
}
e.preventDefault();
}
onlyChars(event: any) {
const e = <KeyboardEvent>event;
if (e.key === 'Tab' || e.key === 'TAB') {
return;
}
let k;
k = event.keyCode; // k = event.charCode; (Both can be used)
if ((k > 64 && k < 91) || k === 8 || k === 32 || (k > 96 && k < 124)) {
return;
}
e.preventDefault();
}
allowDecimal(event: any) {
const e = <KeyboardEvent>event;
if (e.key === 'Tab' || e.key === 'TAB') {
return;
}
let k;
k = event.keyCode; // k = event.charCode; (Both can be used)
if ((k == 48) || (k == 49) || (k == 50) || (k == 51) ||
(k == 52) || (k == 53) || (k == 54) || (k == 55) ||
(k == 56) || (k == 57)) {
var arcontrol = new Array();
var temp = this.inputElement.nativeElement.value;
arcontrol = this.inputElement.nativeElement.value.split(".");
if (arcontrol.length == 1) {
if (arcontrol[0].length < 16) {
return;
}
else {
}
}
else {
return;
}
}
else if (k == 46) {
var sCount = new Array();
sCount = this.inputElement.nativeElement.value.split(".");
if ((sCount.length) - 1 == 1) {
}
else {
return;
}
}
e.preventDefault();
}
notAllowSpaceatFirst(event: any) {
if (event.target.selectionStart === 0 && event.code === "Space") {
event.preventDefault();
}
else {
if (this.appDirectives === 'integer') {
this.integerOnly(event);
} else if (this.appDirectives === 'noSpecialChars') {
this.noSpecialChars(event);
}
else if (this.appDirectives === 'onlyChars') {
this.onlyChars(event);
}
else if (this.appDirectives === 'allowDecimal') {
this.allowDecimal(event);
}
}
}
}
Component.ts
<h1>Directives:</h1>
<div>
<p>Space At Start Not Allowed</p>
<input appDirectives="" type="test" placeholder="Enter text">
</div>
<div>
<p>Integers Only</p>
<input appDirectives="integer" type="test" placeholder="Enter text">
</div>
<div>
<p>Characters Only</p>
<input appDirectives="onlyChars" type="test" placeholder="Enter text">
</div>
<div>
<p>Special Characters Not Allowed</p>
<input appDirectives="noSpecialChars" type="test" placeholder="Enter text">
</div>
<div>
<p>Allow Decimal</p>
<input appDirectives="allowDecimal" type="test" placeholder="Enter text">
</div>
Find source code on github
https://github.com/pratik-maurya/Directives/tree/masterShare this:
- Share on Facebook (Opens in new window) Facebook
- Share on X (Opens in new window) X
- Share on WhatsApp (Opens in new window) WhatsApp
- Email a link to a friend (Opens in new window) Email
- Share on Pinterest (Opens in new window) Pinterest
- Share on LinkedIn (Opens in new window) LinkedIn
- Share on Threads (Opens in new window) Threads
- Share on Telegram (Opens in new window) Telegram










3 Comments
Your comment is awaiting moderation.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://www.binance.com/register?ref=IXBIAFVY
Your comment is awaiting moderation.
the blackjacks
References:
kairoskonnectinc.com
Your comment is awaiting moderation.
firekeepers casino
References:
pattern-wiki.win
Your comment is awaiting moderation.
genting casino southend
References:
https://urlscan.io/result/019a71ea-3929-77d9-868c-bfa96415b60a/
Your comment is awaiting moderation.
Your article helped me a lot, is there any more related content? Thanks! https://www.binance.info/register?ref=IHJUI7TF
Your comment is awaiting moderation.
sbg global mobile
References:
noticiasenvivo.top
Your comment is awaiting moderation.
mostbet mobil aviator mostbet mobil aviator
Your comment is awaiting moderation.
mostbet sms gəlmir mostbet sms gəlmir
Your comment is awaiting moderation.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://www.binance.com/register?ref=QCGZMHR6
Your comment is awaiting moderation.
Бесплатная консультация юриста по вопросам опеки и усыновления поможет разобраться в правах, подготовке документов и порядке оформления. Переходите по запросу юридические услуги по усыновлению – специалист подскажет, как действовать в вашей ситуации, оценит риски и предложит оптимальное решение. Получите профессиональную помощь по делам опеки и попечительства на каждом шаге без лишних затрат.
Your comment is awaiting moderation.
Brain, Mind and Consciousness laboratory The Brain, Mind and Consciousness laboratory investigates high-level cognitive processes using brain imaging (fMRI), behavior and introspective reports. We are particulary interested in areas of overlap, as well as separation, between psychological processes involved in social cognition, mechanical reasoning, attention and self-awareness.
Your comment is awaiting moderation.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me? https://www.binance.com/join?ref=IHJUI7TF
Your comment is awaiting moderation.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article. https://www.binance.com/hu/register?ref=IQY5TET4
Your comment is awaiting moderation.
Explore more at https://thewhitefang.com. From durable skateboards for smooth rides to UV-protective beach tents and golf practice nets, each product focuses on performance and ease of use. Built with quality materials and smart design, WhiteFang gear helps you stay active, relaxed, and ready for every outdoor moment.
Your comment is awaiting moderation.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you. https://www.binance.com/register?ref=IXBIAFVY
Your comment is awaiting moderation.
xn88 cung cấp số hotline hỗ trợ khách hàng 24/7: (+44) 2036085161 hoặc (+44) 7436852791. Tuy nhiên, do chênh lệch múi giờ, bạn nên liên hệ qua các phương thức khác như trò chuyện trực tiếp, email hoặc Zalo để được hỗ trợ nhanh chóng hơn. TONY03-07O
Your comment is awaiting moderation.
Không cần fake IP, không lo chặn link – 188V – Nhà cái trực tuyến uy tín cho cược thể thao và casino cung cấp đường vào ổn định qua đại lý chính thức, giúp bạn truy cập mượt mà mọi lúc, mọi nơi. TONY03-07O
I like this blog very much, Its a really nice office to
read and get info.
Best blog for developers.
Wow! This blog looks exactly like my old one! It’s on a entirely
different subject but it has pretty much the same layout
and design. Excellent choice of colors!