why i am not able to make the text area partially non editable in angular 5 and typescript?

拜拜、爱过 提交于 2019-12-11 15:26:05

问题


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 editable in this text area.

So for example from my components ts file i can set the initial value, for example : "RMO " to my text area .

The user cannot remove the text "RMO " which is set in the text area.

i have got some jquery code to achieve this (http://jsfiddle.net/zq4c873L/1/) and i convert it to typescript code. however it is not working as well

so this is my text area defined in the components html template.

<textarea id="messageTxt" formControlName="message" rows="6" [placeholder]="'PLACEHOLDERS.MESSAGE' | translate" (keydown)="ensureMessagePrefixNonEditable(messageTxt.value)" (keyup)="calculateMessagingSegmentCount(messageTxt.value)" #messageTxt></textarea>

there is a function that is triggered whenever the user press a key down. ie ensureMessagePrefixNonEditable(messageTxt.value). this function tries to replace the old value if it doesn't match the text area content with a specific search string. The following is my function .

ensureMessagePrefixNonEditable(inputTxtMsg: string){
 console.log(inputTxtMsg);
    let originalValue: string = inputTxtMsg;
    if( !inputTxtMsg.startsWith(this.messagePrefix.concat(' ')) ) {
    this.messageControl.setValue(originalValue);
    }
}

however the problem is i am able to remove the predefined value from the text area. any idea what am is wrong in the function ensureMessagePrefixNonEditable. really appreciate any help thank you

i also rewrite my funtion as follows but still the problem

  ensureMessagePrefixNonEditable(inputTxtMsg: string){

    let originalValue: string = inputTxtMsg;

    let messagePrefixSearchWithSpace: string = this.messagePrefix.concat(' ');

    let regex: RegExp = new RegExp("^" + originalValue+ "$");

    if(!regex.test(messagePrefixSearchWithSpace)){
      this.messageControl.setValue(originalValue);
      this.formGroup.patchValue( {message: originalValue });
    }

  }

i can see it enters inside the if block, however this.formGroup.patchValue( {message: originalValue }); didnt set the message text area with the original string in the UI.

Thank you


回答1:


angular reactive forms version using ngModelChange event handler

private currentValue = "";

constructor(
    private formBuilder: FormBuilder,
) {
    this.loginForm = this.formBuilder.group({
        messageTxt: ["", Validators.required]
    });
}

public async ngOnInit() {
    this.loginForm.controls["messageTxt"].setValue("RMO");
    this.currentValue = "RMO";
}

public keepRMO($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>



回答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:

<textarea regexDirective="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 reusable

        constructor(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 anything
                return;
            }  else {
                e.preventDefault();
            }
        }
    }


来源:https://stackoverflow.com/questions/57290784/why-i-am-not-able-to-make-the-text-area-partially-non-editable-in-angular-5-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!