问题:为什么更改为父中的对象没有显示在子组件中?
当父组件中的对象显示在子组件中时,我很难检测到该对象中的更改值。
父组件模板具有增加值的按钮。
<div class="container root">
<div class="row">
<div class="col-md-12 col-xs-12">
<h1>
{{title}}
</h1>
<button (click)="funct1()" class="btn btn-success btn-lg">A ++</button>
<button (click)="funct2()" class="btn btn-success btn-lg">B ++</button>
<button (click)="funct3()" class="btn btn-success btn-lg">C ++</button>
<button (click)="funct4()" class="btn btn-success btn-lg">D ++</button>
<p *ngFor="let item of details"><strong>name:</strong> {{item.name}}, <strong>id:</strong> {{item.value}}</p>
</div>
<div class="row child">
<div class="col-md-6 col-md-6">
<app-child [data]="details">loading child component</app-child>
</div>
</div>
</div>
</div>
app.component.ts 文件,
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Root component!';
value1: number = 0;
value2: number = 0;
value3: number = 0;
value4: number = 0;
details: {name: string, value:number}[]=[]
arrayBuild(){
this.details = [{name: 'A', value: this.value1}, {name: 'B', value: this.value2}, {name: 'C', value: this.value3}, {name: 'D', value: this.value4}];
}
funct1(){
this.value1++;
this.arrayBuild();
}
funct2(){
this.value2++;
this.arrayBuild();
}
funct3(){
this.value3++;
this.arrayBuild();
}
funct4(){
this.value4++;
this.arrayBuild();
}
}
child.component.ts
import { Component, OnInit, Input, OnChanges } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit, OnChanges {
@Input() data: {name: string, value: number}[] = [];
constructor() { }
ngOnInit() {
}
ngOnChanges(){
}
}
child.component.html
<div class="child">
<h3>Child Component!</h3>
<p *ngFor="let element of data"><strong>name:</strong> {{element.name}}, <strong>id:</strong> {{element.id}}</p>
</div>
我认为这将与生命周期钩子有关,我只是模糊地熟悉。
github上的代码在这里。谢谢,