Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular5, Interaction between components

Currently following a Angular5 course and after doing research for some time on the topic I still don't understand the following fully:

Code:

App.component.html:

      <app-server-element 
      *ngFor="let serverElement of serverElements"
      [element]="serverElement"
       ></app-server-element>

App.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  serverElements = [{type: 'server', name:'Testserver',content:'just a test!'},
                    {type: 'server', name:'Testserver',content:'just a test!'}
];  
   }

server-element.component.html:

  <p>
    <strong *ngIf="element.type === 'server'" style="color: red">
{{ element.content }}</strong>
    <em *ngIf="element.type === 'blueprint'">{{ element.content }}</em>
  </p>

server-element.component.ts:

import { Component, OnInit,Input } from '@angular/core';

@Component({
  selector: 'app-server-element',
  templateUrl: './server-element.component.html',
  styleUrls: ['./server-element.component.css']
})
export class ServerElementComponent implements OnInit {
 @Input() element: {type:string, name:string, content:string};
}

Question:

I'm a bit confused what this part does:

  *ngFor="let serverElement of serverElements"
  [element]="serverElement"

In my current understanding it is a for loop which loops through all the elements of the serverElementsArray. But then what does [element]="serverElement"do specifically?

like image 547
Willem van der Veen Avatar asked Jan 03 '23 05:01

Willem van der Veen


1 Answers

You are totally right about the loop through all elements of serverElementsArray.

Using [element]=... you bind the input of component. Read on... :-)

Notice where is it looped on - app-server-element component. I assume that this component is responsible for printing our server detail.

But you have to somehow provide it the server which it should print out. And thats where [element]=... comes to play

Notice the @Input() element part of ServerElementComponent. This defines that component accepts some input value.

So using [element]=... you bind a single serverElement to the @Input called element in ServerElementComponent. There will be multiple ServerElementComponents for each item in the loop.

like image 180
Martin Nuc Avatar answered Jan 18 '23 21:01

Martin Nuc