一. 组件间通信
@Input @Output 输入输出属性
ng g c child
1.父传子:
app.component.html
<app-child [myName]="name"></app-child>
app.component.ts
export chlass AppComponent{
name="父组件的name"
}
child.component.html
<div>{{myName}}</div>||<div>{{otherName}}</div>
child.component.ts
@Input() myName;||@Input("myName") otherName;
2.子传父
–child.component.ts
export class ChildComponent implements OnInit {
childname = "子组件名字 传到赋组件";
@Output("myEvent") myEvent123 = new EventEmitter();
handleClick() {
console.log('zizujian');
this.myEvent123.emit(this.childname)
}
constructor() { }
ngOnInit() {
}
}
child.component.html
<button (click)="handleClick()">1231231</button>
app.component.html
<app-child (myEvent)="handleEvent($event)"></app-child>
app.component.ts
handleEvent(e) {
console.log('父组件定义被触发 ')
console.log(e)
}
点击按钮打印
zizujian
父组件定义被触发
子组件名字 传到赋组件
3. 中间人模式 (子1->父->子2)
4. 观察者模式(订阅发布模式)
二 引用
<input type=“text” #username />
<button (click)=“handleClick(username)”> 这样可以获取原生dom
在组件中 是无法直接通过this.username 访问到的
@ViewChild("username") name123:ElementRef;
console.log(this.name123.nativeElement.value);//这样就可以访问到了
三 ng-content
<ng-content></ng-content> 相当于 vue中slot 插槽,能把在父组件中写的东西拿到子组件中。
四 生命周期
(1)ngOnChanges:被绑定的输入属性值发生改变时调用,首次调用一定在ngOnInit之前,
"输入数据"指的是通过@Input装饰器显式指定的那些数据。每次父组件传入子组件的属性值变化时, 这个方法都会重新调用。
(2)ngOnInit: 初始化,(数据请求)
(3)ngDoCheck: 在每个angular 检测周期中调用,每次修改了组件内部的状态,就会调用
(4)ngAfterContentInit: 把父组件投射到自己视图后调用,此时可以访问投射的原生dom
(5)ngAfterContentChecked, 检测父组件投射到自己视图的绑定数据改变之后调用
(6)ngAfterViewInit: 初始化组件以及子视图后调用,此时可以访问组件的dom
(7)ngAfterViewChecked 每次做完视图以及子视图更新检测之后调用
(8)ngOnDestroy:销毁调用
*关于ngDoCheck,ngAfterContentChecked,ngAfterViewChecked调用多次的问题?
数据初始化或变化,第一轮触发watches等;第二轮确保数据没有再发生变化,否则还会触发新一轮检测更新。