Prepare a form field response in Angular 2

I am creating an Angular 2 registration form that asks the user to provide the URL of their site before submitting.

When the form is submitted, I need the URL provided to be in the style of " http://www.google.com ". To direct the user to this format, I want the form field to automatically fill in the initial "http: //" as soon as the user clicks on this field (or when the user starts typing - any case will be acceptable). Currently, I have a placeholder text in the field that says: "Please indicate the URL of your site," but I am having problems with the prefix "http: //" when the user actually clicks on the field or starts print.

Any ideas would be appreciated. This is what the form field looks like when the user clicks on it. Its contents should switch to "http: //" when you press or enter in. Here's what the code looks like at the moment:

<div class="form-group">

  <input
    class="form-control"
    type="text"
    name="companyUrl"
    [(ngModel)]="user.companyUrl"
    placeholder="Company url"
    required pattern='https?://.+'
    #companyUrl
   >

    <div *ngIf="companyUrl.errors && (companyUrl.dirty || companyUrl.touched)" class="text-danger">
      <div [hidden]="!companyUrl.errors.required">
        Company URL is required.
      </div>
      <div [hidden]="!companyUrl.errors.pattern">
        URL should begin with http:// or https://
      </div>
    </div>

<div>
+4
source share
1 answer

Add a function to add a prefix to an input click event. Something like below:

<input #companyUrl  (click)="addHttpPrefix()" >

And in this function 1. Get the value of companyUrl. 2. Check if it starts with http, and then skip the else prepend with http: //

if(companyUrl.indexOf('http') > -1) {
    companyUrl = 'http://' + companyUrl;
}

That way, when the user first clicks on the http: // input, it will be added. if the event (click) does not meet your requirement, you can try to use (change) or other events.

0

Source: https://habr.com/ru/post/1681355/


All Articles