ramya chockalingam
ramya chockalingam

Reputation: 155

How to give fixed text in the form field in angular?

I have two fields.One is Id and another one is URL.My question was how to give fixed text in the fields. In the below code,in the URL field the user has to give the IP address and port number.In that field,there should be fixed text https:\.The user's data should enter after this https:\.while storing in database,the data should like https:\192.145.23.45\7894.

please answer this question.

Thanks in advance:)

<mat-form-field appearance="outline">
   <mat-label>url</mat-label>
   <input matInput placeholder="Url"formControlName="url" >
   <mat-error *ngIf="appawareform.controls.url.invalid  && 
    appawareform.controls.url.touched && 
    !appawareform.controls.url.value">url is required</mat-error>
   <mat-hint align="start">NOTE:server:portno</mat-hint>
</mat-form-field>

Upvotes: 2

Views: 2975

Answers (2)

AVJT82
AVJT82

Reputation: 73367

Since you are using reactive forms, it is not recommended (and also deprecated) to use ngModel with reactive forms. I bring this up, since the other answer uses it.

Instead I would recommend to listen to valueChanges of the form, and always append the https:// to the formcontrol. We can use rxjs filter to filter out when value is https://

Then you can use a custom validator to check the value (since Validators.required does not apply in this case, as control will always have value https:// no matter what) and either set a custom error or return null, which is considered as valid.

So I suggest the following:

import { filter } from 'rxjs/operator'

ngOnInit() {
  this.appawareform = this.formBuilder.group({
    url: ["https://", this.validateUrl]
  });

  this.appawareform.get("url").valueChanges.pipe(
    filter(value => value !== 'https://')
  ).subscribe(value => {
    this.appawareform
      .get("url")
      // we need to add emitEvent:false to avoid infinite loop
      .patchValue("https://" + value.substring(8), { emitEvent: false });
  });
}

validateUrl(c: FormControl) {
  return c.value === "https://" ? { notValid: true } : null;
}

Then in template you check for this error:

<mat-error *ngIf="appawareform.hasError('notValid', 'url')>...</mat-error>

Then also remember to unsubscribe from valueChanges when component is destroyed!

STACKBLITZ

P.S, this does not check that that what user types is a valid IP and port. You would need to extend the custom validator to check that also. But since that is not the scope of your question, I'm not including that.

Upvotes: 2

akpgp
akpgp

Reputation: 841

You can do it by adding a simple function on the input field.

(focusin)="addPrefix($event)"

Please see the working demo.

Upvotes: 2

Related Questions