Angular: Creating an input field with preset value that is immutable

I am a beginner with angular and I have been working on this code snippet:

<mat-form-field appearance="outline" 
  class="col-30" id="mat-identifier">
  <mat-label>
    {{'columns.dashboard.identifier' | translate}} {{selectedIdentifier?.mandatorieIdentifier ? '*' : ''}}
  </mat-label>
  <input matInput [value]="selectedIdentifier?.standardIdentifier" 
    formControlName="identifier" maxlength="255" 
    (input)="limitcarateres('identifier', 255, $event)">
  <mat-hint *ngIf="showPackage!=true && selectedIdentifier && selectedIdentifier?.tag !== 'OTHERS'">
  {{
    selectedIdentifier?.standardIdentifier + 
    (dataCorrespondenceForm.get('identifier').value !== null  && dataCorrespondenceForm.get('identifier').value !== '' 
     ?  '-' + dataCorrespondenceForm.get('identifier').value : '')
  }}
  </mat-hint>
</mat-form-field>

I need the input to display a default value set by a variable which cannot be deleted by the user. The user should only be able to write additional content after the default value. As an illustration, if # represents the default values and numbers represent user-inputted values, it should look like this: ####123456. The user can delete the numbers but not the #, as they were predefined.

Answer №1

To achieve this effect using CSS, you can include a span with the placeholder text and then position it absolutely within the container. The input element will have padding to ensure the prefix remains fixed in its position.

.placeholder-prefix .mat-mdc-form-field-input-control{
  padding-left: 50px;
}

.placeholder-prefix .prefix{
  position: absolute;
  left: 5px;
  top: 29px;
  font-size: 12px;
}

.placeholder-prefix .mat-mdc-form-field-infix {
  display: flex;
}

.mat-focused.placeholder-prefix .prefix{
  position: absolute;
  left: 5px;
  top: 24px;
  font-size: inherit;
}

Here is an example of how to implement this in HTML:

<form class="example-form">
  <mat-form-field class="example-full-width" class="placeholder-prefix">
    <span class="prefix"&rt;XXXX</span>
    <mat-label>Favorite food</mat-label>
    <input matInput type="text" id="test" name="test" />
  </mat-form-field>
</form>

If you would like to see a live demo, check out this Stackblitz Demo

Answer №2

Aside from the simple HTML/CSS method presented by @naren-murali, you could also utilize a mask library like ngx-mask. -> https://www.npmjs.com/package/ngx-mask

This library includes a prefix feature which fits perfectly for this situation.

If you only have one specific case where you require this functionality, using a pure HTML/CSS solution may be sufficient. However, if you find yourself needing similar features in multiple instances, it might be worth exploring ngx-mask.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best approach to transform a lengthy collection of 'watch' statements into a functioning solution using VueJS?

I am new to vueJS and need some help with optimizing my code. I have a long list of watch functions that are all essentially the same, but I'm not sure how to convert them into a more efficient and functional approach. These watch functions are all r ...

Warning in TypeScript when attempting to modify a single state property within a React component

Imagine we have a simple react Component: import React, { Component } from 'react'; interface IState { a: boolean; b: string; c: number; } class Test extends Component<{}, IState> { state = { a: true, b: 'value' ...

What is the meaning of the term writeHead?

Upon reviewing a GroupMe bot template in nodejs, I noticed a common occurrence of the function call res.writeHead(200);. What is the typical purpose of writeHead(200)? Is it a shorthand for "write header"? ...

A step-by-step guide on creating a Decorator using the TypeScript compile API

How can I create a custom class in TypeScript with multiple 'class-validator' decorators to ensure the property types are correct? I am considering using `ts.factory.createDecorator`, but I'm unsure how to obtain a `ts.Expression` for it. ...

Integrate Bootstrap 4 with your Angular 6 or Angular 7 application

Currently working on an Angular project that utilizes Bootstrap 4. Seeking assistance with incorporating SCSS into my Angular application. The question at hand is: Are the steps for adding Bootstrap 4 SCSS in Angular 6 and Angular 7 identical? For exa ...

Guide on transferring a JSON string from a JSP page to a Spring MVC controller

I am facing an issue while trying to pass a simple json string to my controller. The json string is not being received at the controller end. I have other functionalities like inserting, deleting, etc., inside my controller code which work perfectly fine, ...

Unusual CSS rendering hiccup

Using jQuery, I am manipulating the display of an <a> element. Depending on certain keypress events, it adds or removes a class from an <input> element (which controls the display) that is related as a sibling to the mentioned <a>. The i ...

What to do when encountering a problem with HTML, CSS, and JS while loading a webpage from an SD card to a WebView

I am facing an issue while loading an HTML file from the SD card to a webview. The problem is that the CSS, images, and videos are not loading properly in the webview. Compatible with Android 4.4 KitKat and Chrome version Not compatible with versions belo ...

What is the procedure for passing arguments to Google signIn in a NextJS backend?

I am currently working on implementing a role-based Google sign-in feature in a Next.js 13 app using next-auth. This setup involves calling two different tables to create users based on their assigned roles. For the database, I am utilizing mongodb/mongoo ...

The error encountered states that in the Angular typescript method, the term "x" is not recognized as a

In my codebase, I have an entity named Epic which contains a method called pendingTasks() within a class. import { Solution } from '../solutions.model'; import { PortfolioKanban } from '../kanban/portfolio-kanban.model'; import { Kanban ...

The React component does not display text when the object is empty

I have a react component that utilizes a method to extract data from an object and display its status on another component. The issue arises when the application is loading initially; the object's length is 0. Once the data is loaded, the object&apos ...

Creating a div element with a fixed size that remains the same regardless of its content

Check out the code snippet below for displaying an image and title: <div id="eventsCollapsed" class="panel-collapse collapse" ng-controller="videoController"> <div class="panel-body"> <div ...

Steps for setting a background image for a div

I am facing an issue with 3 horizontally aligned images and a background image. The problem is that when I set the background image for the aligned images, it flows over them instead of staying behind. I want the 3 aligned images to be on top of the backgr ...

iPhone-compatible iFrame with adaptable webpage dimensions

While attempting to embed our page on a client's site, everything looks great in a browser and our media queries are functioning properly. However, we encountered an issue when viewing the embedded page inside an iframe on an iDevice. It seems that th ...

Using a SharedModule in Angular2: A Guide

I have a single Angular2 component that I need to utilize across multiple modules. To achieve this, I created a SharedModule as shown below: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-bro ...

What is the process of turning an SVG element into a clickable link?

Is there a way to transform each element within an SVG image embedded in an HTML file into an active link? I want to create an SVG image with clickable elements. Here is a snippet of the SVG image: <svg version="1.1" id="Layer_1" xmlns="http://www.w3 ...

Having trouble accessing the inline transform scale with jQuery

I am working on a new feature where I need to extract the inline transform scale value from each list item (li). Below is a demonstration for you to assist me: HTML <div style="color:red;transform:scale(1);">Dummy content</div> JS $(functi ...

"Troubleshooting the issue of ng-init not functioning properly in conjunction

I need help with displaying a list of numbers inside a div element. I am attempting to achieve this using the following code snippet: <div ng-init="range=[1,10,3,4,5]" ng-repeat="n in range" > {{n}} </div> Unfortunately, the numbers withi ...

AngularJS Uncaught ReferenceError: variable is not

I am facing an issue where I cannot retrieve a value from a function. I am performing REST requests for testing purposes and when trying to get a date, it always returns undefined. An Illustration $http.get('app/components/home/controller/test_calen ...

Click on a button to completely remove all JavaScript from your website using jQuery

I'm currently experiencing some difficulties with my website Concept Studio. On a specific page, I have a typing animation within a form and I'd like to include a button that allows users to skip the animation. However, I'm unsure of how to ...