Tips for implementing md-icon in combination with md-autocomplete in Angular Material Design:

How can I include an md-icon in an md-autocomplete field?

   <md-autocomplete 
       md-selected-item="ctrl.selectedItem"
       md-search-text-change="ctrl.searchTextChange(ctrl.searchText)"
       md-search-text="ctrl.searchText"
       md-items="item in ctrl.querySearch(ctrl.searchText)"
       md-item-text="item.display"
       placeholder="What is your favorite US state?">

   <md-icon class="material-icon">search</md-icon> // It may not work as expected

  </md-autocomplete>

Check it out on CodePen

Answer №1

Angular-material does not currently support this feature out of the box. However, there is a workaround using custom CSS.

If you are interested in implementing this functionality, check out this resolved issue.

To see an example of how to achieve similar results, visit this functional demo.

HTML: (pay attention to the id and md-input-name attributes)

<md-autocomplete id="custom" md-input-name="autocompleteField".../>

CSS:

#custom input[name="autocompleteField"]  {
    background: url(images/search.icon.png);
    background-repeat: no-repeat;
    background-position: 5px 7px;
    padding: 0px 35px;
}

We hope that this information proves useful for your project.

Answer №2

When searching for a way to add an icon to angular material autocomplete, this is one of the top resources.

To achieve the same result with the new angular material, simply insert the mat-icon after the input field.

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
      <mat-icon matSuffix>search</mat-icon>
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

Explore an example on stackblitz: https://stackblitz.com/angular/kbmrnjeydjm

Answer №3

One potential method is to attach the icon to the md-input-container within the md-autocomplete. This container is only added if the md-floating-label attribute is utilized.

In JavaScript: Using a timeout and compilation was necessary for the icon to display. By adding the md-icon-left class, the input gains a padding of 36px, similar to other md-input-containers with icons.

The attrs[vm.name] will utilize the attribute value as the icon name.

 ...
 .directive('appendIcon', appendIcon);

 function appendIcon($timeout, $compile) {
   return {
     restrict: 'A',
     link: function(scope, elem, attrs) {
       var vm = this;
       $timeout(function() {
         var container = angular.element(elem[0].querySelector('md-input-container'));

         container.addClass('md-icon-left');
         var icon = $compile('<md-icon class="material-icons">' + attrs[vm.name] + '</md-icon>')(scope);
         container.append(icon);
       });
     }
   };
 };

In HTML: Take note of append-icon="search" and md-floating-label="State."

<md-autocomplete 
  append-icon="search"
  md-floating-label="State"
  id="custom" flex="" 
  required=""

Check out the codepen here: http://codepen.io/eydrian/pen/ZLdgwQ

Answer №4

My preference lies with the approach outlined below, which allows for the utilization of .svg icons. This methodology not only enables the continued use of Material Design icons but also facilitates the creation of buttons that can trigger various events like opening a menu, providing help information, and more.

<div style="float: left; padding: 25px 10px 0 4px;">
    <md-icon md-svg-icon="/images/icons/email.svg" class="input-icon-color"></md-icon>
</div>
<div style="overflow: hidden;">
    <md-autocomplete 
        md-selected-item="ctrl.selectedItem"
        md-search-text-change="ctrl.searchTextChange(ctrl.searchText)"
        md-search-text="ctrl.searchText"
        md-items="item in ctrl.querySearch(ctrl.searchText)"
        md-item-text="item.display"
        placeholder="What is your favorite US state?">

        <md-icon class="material-icon">search</md-icon>
    </md-autocomplete>
</div>

The provided style code emulates the color scheme of the .svg icons when integrated into an <md-input-container>:

<style>
.input-icon-color {
    color: rgba(0,0,0,0.87);
}
</style>

Answer №5

It appears that the issue is related to md-autocomplete containing an md-input-container within it.

To solve this problem and create a row of evenly spaced input fields with the first one being md-autocomplete, I had to enclose the other two md-input-containers in flexed divs.

<div layout="column" layout-gt-xs="row">
    <div layout="row" flex layout-align="start start">
      <md-input-container>
      <!-- Angular Material requires md-icon to be surrounded by a div element -->
        <div><md-icon class="yellow-fg" md-font-icon="icon-white-balance-sunny"></md-icon></div>
      </md-input-container>
      <md-autocomplete flex usual_attributes_here>
        (...)
      </md-autocomplete>
    </div>
    <div layout="row" flex>
      <md-input-container flex>
        <md-icon md-font-icon="icon-numeric"></md-icon>
        (...)
      </md-input-container>
    </div>
    <div layout="row" flex>
      <md-input-container flex>
        <md-icon md-font-icon="icon-numeric"></md-icon>
        (...)
      </md-input-container>
    </div>
</div>

https://i.sstatic.net/FCYNx.png

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

Group data by two fields with distinct values in MongoDB

I have developed a Typescript Node.js application and I am looking to organize documents by two fields, "one_id" and "two_id", based on a specific "one_id" value. Below is the data within my collection: { "_id":"5a8b2953007a1922f00124fd", "one_id ...

Translate Typescript into Javascript for use in React applications

Can anyone assist me in converting this Typescript code to Javascript? function ImageMagnifier({ src, width, height, magnifierHeight = 100, magnifieWidth = 100, zoomLevel = 1.5 }: { src: string; width?: string; height?: string; magnifie ...

Is there a simple method I can use to transition my current react.js project to typescript?

I am currently working on a project using react.js and am considering converting it to typescript. I attempted following an article on how to make this conversion but have run into numerous bugs and issues. Is there a simpler method for doing this conver ...

React component state remains static despite user input

I am currently in the process of developing a basic login/signup form using React, Typescript (which is new to me), and AntDesign. Below is the code for my component: import React, { Component } from 'react' import { Typography, Form, Input, But ...

Callback for dispatching a union type

I am currently in the process of developing a versatile function that will be used for creating callback actions. However, I am facing some uncertainty on how to handle union types in this particular scenario. The function is designed to take a type as inp ...

Potential uncertainty in Angular FormControl email validation due to potential null Object

Whenever I run the command ng s --aot, I encounter this message: Object is possibly 'null'. I've been trying various solutions all morning to resolve it, but without success. The issue seems to be related to objects like email.valid, dirty, ...

In what ways does PROJEN streamline project configuration for infrastructure and application projects?

Exploring PROJEN and AWS CDK has raised questions for me regarding how PROJEN contributes to standardizing project configurations in the context of multiple projects or repositories. While I see its usefulness for a single project or repository through the ...

Mastering the Art of Mocking Asynchronous Methods in Node.js Using Jest

I have the following files: |_ utils.js |_methods.js I am currently conducting unit testing for rest.js methods, where the content of the file is as follows: methods.js import Express from 'express' import { add_rec } from './utils' ...

Convert all existing objects to strings

I have a type that consists of properties with different data types type ExampleType = { one: string two: boolean three: 'A' | 'Union' } Is there an easier way to define the same type but with all properties as strings? type Exam ...

Encountering a NPM error when trying to launch the server using ng serve

I encountered an error : ERROR in /opt/NodeJS/FutureDMS/src/app/app.module.ts (5,9): Module '"/opt/NodeJS/FutureDMS/src/app/app.routing"' has no exported member 'APP_ROUTE'. Within my code, I have utilized arrow function in the loadCh ...

Issue encountered: NPM error, unable to find solution for resolving dependency and addressing conflicting peer dependency

I am facing difficulties deploying my project on netlify due to NPM errors. Below are the dependencies: "dependencies": { "@angular/animations": "~15.1.1", ... (list of dependencies continues) ...

A guide on incorporating and utilizing PhotoSwipe in Aurelia / Typescript applications

I've been attempting to integrate PhotoSwipe into my Aurelia project, but I'm struggling to get it working. Within my aurelio.json file under bundles, I've included: { "name": "photoswipe", "path": "../node_modules/photoswipe/dist/ ...

Internationalization in Angular (i18n) and the powerful *ngFor directive

Within my Angular application, I have a basic component that takes a list of strings and generates a radio group based on these strings: @Component({ selector: 'radio-group', templateUrl: `<div *ngFor="let item of items"> ...

In React Typescript, there is an issue with react-router v4 where the Route component does not pass its props to the specified component

Struggling with React Router v4 and history usage in Browserrouter. Whenever attempting to access this.props.history.push("/"), the error pops up: TS2339: Property 'history' does not exist on type 'Readonly<{ children?: ReactNode; }> ...

Is there a way to set an antd checkbox as checked even when its value is falsy within an antd formItem?

I'm currently looking to "invert" the behavior of the antd checkbox component. I am seeking to have the checkbox unchecked when the value/initialValue of the antD formItem is false. Below is my existing code: <FormItem label="Include skills list ...

When initially compiling Angular 5, an error (TS2339) may occur, but after a successful compilation, everything runs smoothly

In a unique scenario, I wrote code that fetches information from an API server without knowing the structure of the response fields. Once I receive the response, I need to create a form for updating the data and sending it back. To handle unknown ngModel p ...

Defined interface with specific number of members

I am tasked with creating an interface that has only two members, one of which is optional and both have undefined names. Something like: interface MyInterface { [required: string]: string|number [optional: string]?: string|number } Unfortunately, ...

Adjust the selected value in real-time using TypeScript

Hey there, I've got a piece of code that needs some tweaking: <div> <div *ngIf="!showInfo"> <div> <br> <table style="border: 0px; display: table; margin-right: auto; margin-left: auto; width: 155%;"& ...

Enhance the background property in createMuiTheme of Material-UI by incorporating additional properties using Typescript

I've been attempting to include a new property within createMuiTheme, but Typescript is not allowing me to do so. I followed the instructions provided here: https://next.material-ui.com/guides/typescript/#customization-of-theme I created a .ts file ...

Steps for displaying detailed information about a single product on an Ecommerce page

Currently in the process of developing my Ecommerce project, I have successfully created a product grid with links to each specific product. However, I am facing an issue where I am unable to view the data of each individual item. Below is the code for my ...