Angular6学习笔记

工作以来学习Angular6也已经有一段时间了,针对平时的学习主要做一下总结,都是平时需要掌握的一些重要的知识点,比较容易遗忘所以先记录下来,方便后面的复习。

一、父子组件的传值

父子组件的传值
组件与组件之间的传值是非常重要的知识点,记录一下最近学习的父子组件之间传值的知识点。
1.父组件向子组件传值
使用@Input()装饰器可以将父组件的数据传递给子组件
使用案例
parent.html

1
2
<p>我是父组件</p>
<app-child [info]=data></app-child>//

parent.ts

1
data="你好,我是父组件的data"

child.html

1
2
<p>我是子组件</p>
<p>父组件的值是:{{info}}</p>

child.ts

1
2
3
@Input() info;
//使用Input()装饰器接收通过路由绑定的参数,
//参数名info与[info]=data中的info保持一致即可得到父组件的信息;

2.子组件向父组件传值
通过使用@ViewChild()装饰器获得子组件的信息
使用案例
parent.html

1
2
3
<app-child #instance></app-child>
<button (click)='getChildMsg()'>获取子组件的Msg</button>
<button (click)='getChildFun()'>获取子组件的Fun</button>

parent.ts

1
2
3
4
5
6
7
@ViewChild('instance') instance:any;//此处就获得了child的整个实例
getChildMsg(){
alert(this.instance.msg)//调用child组件的msg属性
}
getChildFun(){
this.instace.run();//调用child组件的run()方法
}

child.html

1
<p>我是子组件</p>

child.ts

1
2
3
4
msg: string='我是子组件的信息'
run(){
alert('我是子组件的run方法')
}