1、在子组件child.component.ts上面的更改
export class ChildComponent implements OnInit, OnChanges {
@Input()
greeting: string;
@Input()
user: {name: string};
message: string = "初始化消息";
constructor() { }
ngOnInit() {
}
ngOnChanges(changes: SimpleChanges) {
console.log(JSON.stringify(changes,null,2));
}
}
2、在child.component.html上面的更改
<div class="child">
<h2>我是子组件</h2>
<div>问候语{{greeting}}</div>
<div>姓名{{user.name}}</div>
<div>消息:<input [(ngModel)]="message"> </div>
</div>
给子组件和父组件添加了背景颜色,更好区分组件关系
3、修改app.component.ts
export class AppComponent {
// 父组将需要给子组件传递数据,所有同样声明这两个属性
greeting: string = "hello";
user: {name: string} = {name: "Tom"};
}
4、修改app.component.html
<div class="parent">
<h2>
我是父组件
</h2>
<div>
<!--这里面需要演示的是ngOnChanges属性,也就是说需要改变输入属性的值 所有在父组件上,这个问候语这个属性不是单向绑定出来的,而是双向绑定-->
问候语:<input type="text" [(ngModel)]="greeting">
</div>
<div>
姓名:<input type="text" [(ngModel)]="user.name">
</div>
<app-child [greeting]="greeting" [user]="user"></app-child>
</div>
可在控制台上看组件操作前后的变化。
父组件初始化子组件输入属性之前,子组件的输入属性是没有值的,然后ngOnChanges方法会被调用,子组件的输入属性被初始化,
这里面只有greeting触发了OnChanges方法,可变对象(user)的属性(name)改变不会触发ngOnChanges方法,但是子组件的user属性仍然跟随父组件变化而改变,这是因为angular的变更检测机制捕获到了每个对象的变化