Angular dropdown option not displaying tick mark

I'm attempting to add a tick mark before a specific default item in the option dropdown of my Angular application. The item in question is named Steven, as shown in this example. How can I make this happen?

For some reason, it doesn't seem to be working.

To demonstrate the issue, I've created a StackBlitz: https://stackblitz.com/edit/angular-ivy-qac8ae?file=src/app/app.component.html

Here is the markup:

<form [formGroup]="form">
  <div class="wrapper">
    <div class="select-wrapper-row">
      <select formControlName="name">
        <option value="">-- Select an option --</option>
        <option
          *ngFor="let item of nameList$ | async"
          [ngClass]="{ checkmark: item.isAlive == true }"
          [selected]="item.isAlive"
        >
          {{ item.name }}
        </option>
      </select>
    </div>
  </div>
</form>

And here's the CSS:

.checkmark:before {
  content: 'L';
  font-family: arial;
  -ms-transform: scaleX(-1) rotate(-35deg); /* IE 9 */
  -webkit-transform: scaleX(-1) rotate(-35deg); /* Chrome, Safari, Opera */
  transform: scaleX(-1) rotate(-35deg);
  display: inline-block;
  vertical-align: top;
  line-height: 1em;
  width: 1em;
  color: white;
  height: 1em;
  margin-right: 0.6em;
  text-align: center;
  position: absolute;
  right: 0;
}

Answer №1

Unfortunately, I encountered difficulties in getting your stackblitz to work properly.

An error occurred in ~/src/main.ts
ngcc was unable to execute on @angular/[email protected].

Nevertheless, the solution can still be illustrated using a simple HTML snippet:

body {
  width: 50vw;
}

div {
  border-bottom: 1px dotted green;
}

.checkmark {
  /* without this checkmark will not be 
      placed relative to the item */
  position: relative;
}

.checkmark:before {
  content: 'L';
  font-family: arial;
  -ms-transform: scaleX(-1) rotate(-35deg);
  /* IE 9 */
  -webkit-transform: scaleX(-1) rotate(-35deg);
  /* Chrome, Safari, Opera */
  transform: scaleX(-1) rotate(-35deg);
  display: inline-block;
  vertical-align: top;
  line-height: 1em;
  width: 1em;
  /* unless your background is dark don't use white as text color */
  color: white;
  height: 1em;
  margin-right: 0.6em;
  text-align: center;
  /* if you want it on left side then remove this*/
  position: absolute;
  right: 0;
}

.change1::before {
  color: green;
}

.change2::before {
  position: static;
}

.checkmarkFixed:before {
  content: 'L';
  font-family: arial;
  -ms-transform: scaleX(-1) rotate(-35deg);
  /* IE 9 */
  -webkit-transform: scaleX(-1) rotate(-35deg);
  /* Chrome, Safari, Opera */
  transform: scaleX(-1) rotate(-35deg);
  display: inline-block;
  vertical-align: top;
  line-height: 1em;
  width: 1em;
  color: green;
  height: 1em;
  margin-right: 0.6em;
  text-align: center;
}

select {
  width: 100px;
}

option:checked {
  background-color: gray;
}
<div class='checkmark'>Your code: not working</div>
<div class='checkmark change1'>Correction 1</div>
<div class='checkmark change1 change2'>Correction 2</div>
<div class='checkmarkFixed'>Fixed</div>

<select size=5>
  <option value="1" class='checkmark change1'>One</option>
  <option value="3" class='checkmark change1 change2'>Two</option>
  <option value="2" class="checkmarkFixed">Three</option>
  <option value="4" selected>Four</option>
  <option value="5">Five</option>
</select>

  • You have selected white as the color for the thickmark. It may not be visible unless the background is dark.
  • If you prefer the thickmark on the left of the item, avoid using position:absolute.
  • In case you utilize position:absolute, include the .checkmark rule as depicted above.

I intentionally introduced separate .change1 and .change2 classes to demonstrate what changes could resolve the issue. These modifications can be consolidated into one single rule like .checkmarkFixed:before

Answer №2

::before and ::after are pseudo-elements that add a child node to the element, therefore they will not function on elements that cannot hold child nodes - like option.

Another option is to consider using a component such as ng-select, which comes with this feature pre-built.

Answer №3

I have made some improvements and refactored the code a bit. You can check out the example on StackBlitz here:

https://stackblitz.com/edit/angular-ivy-bbnkfufile=src/app/app.component.html

<form [formGroup]="form">
  <mat-select placeholder="select" formControlName="title">
    <mat-option *ngFor="let item of nameList$ | async" [value]="item">
      <div class="option-wrapper">
        <span>
          {{ item.name }}
        </span>
        <span *ngIf="item.isAlive" class="checkmark"></span>
      </div>
    </mat-option>
  </mat-select>
</form>

CSS

p {
  font-family: Lato;
}


.option-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.checkmark:before {
  content: 'L';
  font-family: arial;
  -ms-transform: scaleX(-1) rotate(-35deg);
  -webkit-transform: scaleX(-1) rotate(-35deg);
  transform: scaleX(-1) rotate(-35deg);
  display: inline-block;
  width: 1 em;
  color: black;
  height: 1 em;
}

.mat-option {
  width: calc(100vw - 50px);
}

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

Update the style class of an <img> element using AJAX

My success with AJAX enables PHP execution upon image click. However, I seek a real-time visual representation without page reload. Thus, I aim to alter <img> tag classes on click. Presently, my image tag resembles something like <img title="< ...

What is the recommended approach for returning two different types in a TypeScript function?

My API function currently performs a post request and returns an Observable of ModelAResponse, which is an interface I have defined. I now want to modify this function so that it can return an Observable of either ModelAResponse or ModelBResponse based on ...

After resetting my computer, I am now encountering an error message that states "There is no 'Access-Control-Allow-Origin' header present". Why is this happening?

After reformatting my pc, I encountered a new issue when sending an ajax request which involved calling a php file. The message displayed was: "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' ...

Is Javascript necessary for submitting a form to a PHP script?

In my current project, I am working on a page to edit information in a database. While I know how to create the form in HTML and the PHP script that runs on the server, I am facing a challenge with JavaScript. My understanding of JavaScript is limited, and ...

Html - The 'td' element in the table is not staying fixed

In my project, I have created a table with Start date and End Date as two table data elements. I have implemented some validations that are triggered when certain conditions are not met. However, I noticed that when these validations are fired, it causes t ...

What is the best way to establish a grid system limited to a maximum of 8 rows?

Looking to showcase a grid system with a maximum of 8 lines. The number of cells is variable, whether it's 12, 20, 100, and more. Click here for an image example. ...

What steps should be followed to implement ng-zorro-antd?

I'm currently in the process of developing an Angular project with ng-zorro. I've followed these steps: npm install --location=global @angular/cli ng new ng-zorro-demo This Angular project includes routing. cd ng-zorro-demo/ ng add ng-zorro-antd ...

How can I swiftly load or insert HTML code into an HTML file using jQuery?

I'm currently developing a mobile app using Cordova, essentially an html-based application running in an app wrapper. I have numerous elements and html code that need to be consistent across all pages, such as navigation menus, popups, and more. When ...

Looping through each <li> element using JavaScript, insert an image with a hyperlink that redirects to a different page within every li item

I am looking to iterate through each <li> element and dynamically add an image with a link that redirects to a different page using JavaScript. The goal is to store all images, links, and titles in an array object by utilizing the Document Object M ...

Can an Observable be created that emits an array produced by awaiting asynchronous methods?

I've encountered an issue with the following method: get fileResults$(): Observable<File[]> { return this.ngRedux.select<ICommunicationState>('communication').pipe(map(newState => { const files: File[] = []; ...

What is the best way to eliminate whitespaces and newlines when using "document.execCommand("copy")" function?

I'm currently working on a code that allows users to copy highlighted text without using the keyboard or right-clicking. I also need to remove any extra spaces or line breaks using regex after the text is selected. However, I am facing some issues wit ...

What is the best way to display a collection of cards with each card taking up the full width using a grid layout in Angular Material?

In my Angular 6 and Material project, I have a card component that looks like this: <mat-card> <mat-grid-list cols="12"> <mat-grid-tile colspan="3"><img [src]="urlAvatar" style="width:250px;height:200px"></mat-gr ...

"Seeking guidance on getting my carousel functionality up and running in Angular 8 - any

I tried implementing a carousel from the Bootstrap 4 documentation, but it is only displaying one image. How can I modify the carousel to show all images? I am new to using Angular. Below is the code I have: <div class=" bg-success text-white py-5 tex ...

Generate a download link for the image being shown in a div element

I am working on a project where I need to display HTML content offline within a Windows Application. The application, developed in Autoplay Media Studio, includes an iexplore box to load the HTML. Before the application loads, I have set up a silent insta ...

Tips for avoiding the page from reloading when executing a query. I attempted using preventDefault(); which successfully prevented the reload, but it also stopped PHP

function createCounter() { var count = 0; return function () {return count += 1;} } var add = createCounter(); function updateDatabaseOnClick(){ document.getElementById("result").innerHTML = add(); } I'm currently working on implementing a co ...

Iterating through a set of HTML elements and making updates using a forEach loop

I have encountered an issue while attempting to update a group of HTML elements within a forEach loop. Initially, everything appears to be functioning correctly up to section 3. However, upon adding a new section, the problem arises where the navigation ba ...

Creating clickable links for selected text in React: A step-by-step guide

I've been working on creating a WYSISYG editor and integrating hyperlinking to text selections, but I'm facing some difficulties. Despite searching the internet, I can't seem to figure out why it's not functioning as expected. My appro ...

Phone website doesn't display properly on mobile device (CSS and HTML)

I am experiencing an issue where my website is not loading on mobile devices, but it functions properly when I adjust the size of my Chrome window on my laptop. @media screen { body{ background-image: url(background.jpg); backgroun ...

The Angular 2 http request is malfunctioning, yet I am able to view the JSON response in Postman

I'm currently attempting to retrieve a list of heroes from the backend, which is built using Spring MVC, Rest, and includes CORS (Cross-origin-resource-sharing). Here is the JSON Response: [{"id":1,"name":"Sai"},{"id":2,"name":"Ram"},{"id":11,"name" ...

Encountered an issue with Angular Material sidenav: The synthetic listener @transform.start was found

Click here to visit the StackBlitz link Encountering an issue while attempting to utilize the material side nav. Error message: preview-29b0f46fcc27b310236ab.js:1 ERROR Error: Uncaught (in promise): Error: Found the synthetic listener @transform.start. P ...