Why I Am Not Able To Make The Text Area Partially Non Editable In Angular 5 And Typescript?
I am having an angular project developed using angular 5 and typescript . In my component's html template I have an text area box. I want to make the first few characters non edita
Solution 1:
angular reactive forms version using ngModelChange event handler
private currentValue = "";
constructor(
private formBuilder: FormBuilder,
) {
this.loginForm = this.formBuilder.group({
messageTxt: ["", Validators.required]
});
}
publicasyncngOnInit() {
this.loginForm.controls["messageTxt"].setValue("RMO");
this.currentValue = "RMO";
}
publickeepRMO($event) {
let prefix = "RMO";
if ($event.substring(0, 3) !== prefix) {
alert("You are not allowed to remove the first three characters('RMO')");
this.loginForm.controls["messageTxt"].setValue(this.currentValue);
} else {
this.currentValue = $event;
}
}
html:
<textarea
class="form-control"
name="messageTxt"
id="messageTxt"
formControlName="messageTxt"
rows="6"
(ngModelChange)="keepRMO($event)"
></textarea>
Solution 2:
This is the directive I would use, you might need to adapt it. It check if the text contained in the input match your regex otherwise prevent the keydown.
HTML:
<textarearegexDirective="your regex"></textarea>
Directive:
@Directive({
selector: '[regexDirective]'
})
export class RestrictToPatternDirective {
@Input() appRestrictToPattern = ''; // should be your regex passed as an input in case it needs to be reusableconstructor(private elementRef: ElementRef) { }
@HostListener('keydown', ['$event']) onKeyDown(e: KeyboardEvent): void {
if (new RegExp(this.appRestrictToPattern).test(this.elementRef.nativeElement.value + e.key)) {
// let it happen, don't do anythingreturn;
} else {
e.preventDefault();
}
}
}
Post a Comment for "Why I Am Not Able To Make The Text Area Partially Non Editable In Angular 5 And Typescript?"