Angular 从零开始 3-组件通信 生命周期

本文详细介绍了Angular中的组件间通信方式,包括父传子、子传父、中间人模式及观察者模式。此外还讲解了如何使用@ViewChild获取DOM元素、ng-content的作用以及Angular的生命周期钩子。

一. 组件间通信
@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等;第二轮确保数据没有再发生变化,否则还会触发新一轮检测更新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值