我正在练习各种数据共享方法。在这里,我正在进行简单的父对子数据共享,但无法在子视图中使用/显示父(计数)值。
import { Component} from '@angular/core';
@Component({
selector: 'app-parent',
template: '<app-child [parentCount]="count"></app-child>',
styleUrls: ['./parent.component.css']
})
export class ParentComponent{
count :number = 10;
}
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template:'<div>{{parentCount}}</div>',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input()
parentCount:number;
constructor(){
//console.log(this.parentCount);
}
}
答案 0 :(得分:0)
在ngOninit内部而不是在构造函数内部执行,如下所示
export class ChileComponent {
@Input()
parentCount: number;
ngOnInit() {
console.log('The value we are receiving here is: ' + this.parentCount);
}
}
<强> DEMO 强>
答案 1 :(得分:0)
您将获得ngOnChanges Hook中的值。在子组件中使用以下代码。
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-child',
template:'<div>{{parentCount}}</div>',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnChanges {
@Input()
parentCount:number;
constructor(){
//console.log(this.parentCount);
}
ngOnChanges(changes: SimpleChanges){
console.log(changes.parentCount.currentValue);
}
}
答案 2 :(得分:-1)
你必须从html传递值
<app-child [parentCount]="count"></app-child>