Introduction
- Here we are passing some values from parent component to the child component.
Technically :
- we are binding the property of child component to the parent component.
Here we will see how we can send data to the child component.
Parent Component
Ts file
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
serverElements = [
{
type:'server',
name:'firstserver',
content:'first server contenet'
},
{
type:'blueprint',
name:'firstserver',
content:"first server contenet"
}
];
}
Parent component HTML
<div class="container">
<app-cockpit></app-cockpit>
<hr>
<div class="row">
<div class="col-xs-12">
<app-server-element *ngFor="let serverElement of serverElements" [element]="serverElement"></app-server-element>
</div>
</div>
</div>
- here we have used ngFor for the app-server-Element and we have bind the property in the app-server element to the serverElement ,
Child component
app-server-element
app-server-element ts file
- since by default app properties are private that's why we have to use @Input to bind the property from parent
import { Component, Input, OnInit } 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
};
constructor() { }
ngOnInit(): void {
}
}
Child component HTML
- here we are reading the property values which are bind to the child component.
<div class="panel panel-default">
<div class="panel-heading">{{ element.name }}</div>
<div class="panel-body">
<p>
<strong *ngIf="element.type === 'server'" style="color: red">{{ element.content }}</strong>
<em *ngIf="element.type === 'blueprint'" style="color: rgb(9, 143, 80);">{{ element.content }}</em>
</p>
</div>
</div>