How to work with Angular Arrays with screen printing?

Asked

Viewed 175 times

1

I still know little of Angular and know only the basics, look at the code snippet:

 listarTodas(): Promise<any> {
    return this.http.get(this.cidadesUrl)
      .toPromise()
      .then(response => console.log(response.json()));
  }

Look at the way out!

inserir a descrição da imagem aqui

  • I would like to know how to only print the attribute values code.

  • I would also like to know how to only print values that the code be equal to 1.

I’m only asking for help here because I’ve made several unsuccessful attempts, I’ve searched the Angular documentation on the internet on blogs and forums and I haven’t found it, I really need help!

1 answer

2


You can use the *ngForOf to print the attributes:

<!-- Assumindo que o seu controlador tem uma variavel `cidades` onde guarda o resultado da sua promessa -->
<ul>
    <li *ngFor="let cidade of cidades">
        <span>{{cidade.nome}} => {{cidade.codigoEstado}}</span> 
        <!-- resultados -->
        <!-- Rio Branco => 1 -->
        <!-- ... -->
        <!-- Santos => 6 -->
    </li>
</ul>

The directive *ngFor will run through your array and print all elements that are contained in it. If you add or remove elements from this array, the DOM will be updated automatically.

To print only elements whose codigoEstado === 1, can use the *ngIf:

<ul>
    <li *ngFor="let cidade of cidades">
        <span *ngIf="cidade.codigoEstado === 1">{{cidade.nome}} => {{cidade.codigoEstado}}</span> 
        <!-- resultados -->
        <!-- Rio Branco => 1 -->
        <!-- Cruzeiro Sul => 1 -->
    </li>
</ul>

As the name implies, the Directive *ngIf allows checking which elements are written in the DOM. If the condition of the directive is true, the parent element is written in the DOM. If false, it is removed from the DOM.

Browser other questions tagged

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