How to dynamically update DOM <datalist> with Angular?

Asked

Viewed 56 times

0

I am learning Angular and with difficulty to update the DOM of an Angular form. My goal is to make an email autocomplete, after putting the "@" in an input: the text is captured and shown along with domains that are indexed in an array, but I can’t create a checkbox with the result in the desired input

Until the part of merging the text with the domains I put in the array I managed, I used a map to concatenate with the input text (which is the "domainDatalist"). The question is, how to make a checkbox in the DOM with the elements of the domainDatalist?

app.component.html:

<body ng-app="">


  <input type="email" list="email-domain" (keyup)="emailAutocomplete($event)" [(ngModel)]="domainValue">

<datalist id="email-domain">
    <option [value]="domainDatalist" >{{domainDatalist}}</option>
</datalist>
</body>

app.componentts.


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent  {
  title = 'email-teste';

  public domainValue: string;
  public domainList = [];
  public domainDatalist = [];
  
  public emailAutocomplete($event): string[] {
    if (($event.keyCode === 48 || $event.keyCode === 50) && $event.srcElement.value.slice(-1) === "@") {

        this.domainList = [
          { id: 0, emailDomain: 'google.com' }, 
          { id: 1, emailDomain: 'outlook.com'}
        ];

      let domainDatalist = this.domainList.map(x => this.domainValue + x.emailDomain);

      console.log(domainDatalist)

      return domainDatalist;

    } else {
      this.domainDatalist = [];
    }
  }
}

1 answer

0

First to assemble the options ngfor is used as below:

<datalist id="email-domain">
   <option *ngfor="let item of domainList" [value]="item" >{{item}}</option>
</datalist>

Then inside the method that adds the items in the autocomplete, if only the above code does not work, add in the assignment of your array in the form below:

    this.domainList = [...[
      { id: 0, emailDomain: 'google.com' }, 
      { id: 1, emailDomain: 'outlook.com'}
    ]];

This form forces you to change the variable reference and reassemble the DOM

Browser other questions tagged

You are not signed in. Login or sign up in order to post.