一、兄弟组件如何传值呢?
类似于发布订阅
在主动改变的地方发送一个信号变量,
在被动改变的地方接受这个变量做出响应。
二、父子组件如何传值or数据共享呢?
2.1 父组件获取子组件属性或方法
例如:父组件html模版内,会有很多占位符这些占位符其实就是对应的子组件例如 app-sider 我们为子组件取个id值 #siderChild
然后在父ts内引入这个标签,就像定义变量一样。
@ViewChild('siderChild') sider;
change(){
let node = this.sider.firstNode; # 调用子组件的变量or值
console.log(this.node)
}
2.2 子组件获取父组件属性或方法
同样的例子,假如你已经创建过子组件sider了,那么父模版页面html会有对应的子组件占位符如 app-sider,我们想传递isCollapsed变量给子组件,我们可以按照下面这样做
//父组件定义
isCollapsed = false;
showDetail(){
alert("hahahaha")
}
父html模版
<nz-sider class="menu-sidebar"
nzCollapsible
nzWidth="256px"
nzBreakpoint="md"
[(nzCollapsed)]="isCollapsed"
[nzTrigger]="null">
<app-sider [msg]="isCollapsed" [run]="showDetail"></app-sider>
</nz-sider>
子组件
export class SiderComponent implements OnInit {
@Input() msg:string; //我们只需要在子组件中定义一个变量接收msg就行
@Input() run:any; // 接收父组件传递过来的方法showDetail
constructor() { }
ngOnInit(): void {
this.run(); // 子组件调用父组件的showDetail方法
}
}
怎么样是不是很简单。。