简体   繁体   中英

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 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

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>

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();
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM