1. How do sibling components pass values?
Similar to publish subscribe
Send a signal variable where it is actively changing, and
accept this variable in response where it is passively changing.
Link angular component service to achieve communication
2. How do parent-child components pass values or share data?
2.1 Parent component gets child component properties or methods
For example: In the parent component html template, there will be many placeholders. These placeholders are actually the corresponding subcomponents, such as app-sider. We take an id value for the subcomponent #siderChild
and then introduce this tag in the parent ts, just like the definition variables are the same.
@ViewChild('siderChild') sider;
change(){
let node = this.sider.firstNode; # 调用子组件的变量or值
console.log(this.node)
}
2.2 Child component gets parent component properties or methods
For the same example, if you have already created a child component sider, then the parent template page html will have a corresponding child component placeholder such as app- sider, we want to pass the isCollapsed variable to the child component, we can do as follows
//父组件定义
isCollapsed = false;
showDetail(){
alert("hahahaha")
}
parent html template
<nz-sider class="menu-sidebar"
nzCollapsible
nzWidth="256px"
nzBreakpoint="md"
[(nzCollapsed)]="isCollapsed"
[nzTrigger]="null">
<app-sider [msg]="isCollapsed" [run]="showDetail"></app-sider>
</nz-sider>
Subassembly
export class SiderComponent implements OnInit {
@Input() msg:string; //我们只需要在子组件中定义一个变量接收msg就行
@Input() run:any; // 接收父组件传递过来的方法showDetail
constructor() {
}
ngOnInit(): void {
this.run(); // 子组件调用父组件的showDetail方法
}
}
How is it not very simple. .