Скажите, что это ваш родительский компонент.
import { Component, ViewChild, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements AfterViewInit{
message = "hello again";
friends:string[] = [];
//will add friend to our list of friends array
add(friend){
if(friend.value){
this.friends.push(friend.value);
friend.value = "";
}
console.log(this.friends);
}
ngAfterViewInit() {
}
}
Интерфейс родительского компонента
<div>
<input #friend type="text" placeholder="name of friend" />
<button type="button" (click)="add(friend)">add friend</button>
</div>
<app-to-child message="List of friends" [friends]="friends"></app-to-child>
Теперь дочерний компонент
Используйте @Input decorator с полями, в которые вы хотите получать данные из родительского компонента.
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-to-child',
templateUrl: './to-child.component.html',
styleUrls: ['./to-child.component.css']
})
export class ChildComponent implements OnInit {
@Input() message:string;
@Input() friends:string[];
constructor() { }
ngOnInit() {
}
//this will called when data is passed from parent to child.
ngOnChanges(val){
console.log("change detected");
console.log(val);
}
}
внутри child.component.html
<h5>CHILD COMPONENT</h5>
<p>Message : {{message}}</p>
<div *ngFor="let friend of friends"> {{friend}}</div>
Вы можете узнать больше о component interactions
здесь , быстрой прогулке.