Currently following a Angular5 course and after doing research for some time on the topic I still don't understand the following fully:
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};
}
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?
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 ServerElementComponent
s for each item in the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With