1.响应视图的变更
- 当 Angular 在变更检测期间遍历视图树时,需要确保子组件中的某个变更不会尝试更改其父组件中的属性。因为单向数据流的工作原理就是这样的,这样的更改将无法正常渲染。
- 如果你需要做一个与预期数据流反方向的修改,就必须触发一个新的变更检测周期,以允许渲染这种变更。这些例子说明了如何安全地做出这些改变。
- AfterView 例子展示了 AfterViewInit() 和 AfterViewChecked() 钩子,Angular 会在每次创建了组件的子视图后调用它们。
father.componet.html
<app-after-view-parent></app-after-view-parent>
after-view-parent.compoent.html
<div>
<app-after-view *ngIf="show"></app-after-view>
<div>
<h2>AfterView Logs</h2>
<button pButton type="button" (click)="reset()">Reset</button>
</div>
</div>
after-view-parent.compoent.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-after-view-parent',
templateUrl: './after-view-parent.component.html',
styleUrls: ['./after-view-parent.component.css']
})
export class AfterViewParentComponent implements OnInit {
public show:boolean = true;
constructor() { }
ngOnInit() {
// console.log(`after view parent ngOnInit!`);
}
reset() {
this.show = false;
}
}
after-view.compoent.html
<div>
<div>child view begins</div>
<app-child-view></app-child-view>
<div>child view ends</div>
<p *ngIf="comment">{{comment}}</p>
</div>
after-view.compoent.ts
import { AfterViewChecked, AfterViewInit, ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { ChildViewComponent } from '../child-view/child-view.component';
@Component({
selector: 'app-after-view',
templateUrl: './after-view.component.html',
styleUrls: ['./after-view.component.css']
})
export class AfterViewComponent implements OnInit, AfterViewInit, AfterViewChecked {
public comment:string = '';
public pervHero: string = '';
@ViewChild(ChildViewComponent) viewChild!:ChildViewComponent;
constructor(private cd: ChangeDetectorRef) { }
ngOnInit() {
// console.log(`after viwe ngOnInit!`);
}
ngAfterViewInit() {
console.log(`after viwe ngAfterViewInit`);
this.doSomething();
}
ngAfterViewChecked() {
if(this.pervHero === this.viewChild.hero) {
console.log(`AfterViewChecked (no change)`)
} else {
this.pervHero = this.viewChild.hero;
console.log(`AfterViewChecked`);
this.doSomething();
}
}
doSomething() {
const c = this.viewChild.hero.length > 10?`That's a long name`: '';
if(this.viewChild.hero.length > 10) {
this.comment = c;
//手动脏值检查
this.cd.detectChanges();
}
}
}
child-view.component.html
<div>
<label>Hero Name:</label>
<input type="text" [(ngModel)]="hero"/>
</div>
child-view.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-child-view',
templateUrl: './child-view.component.html',
styleUrls: ['./child-view.component.css']
})
export class ChildViewComponent implements OnInit {
public hero:string = 'Magneta';
constructor() { }
ngOnInit() {
// console.log(`child view ngOnInit!`);
}
}
运行效果:


本文详细讲解了Angular 8中AfterViewInit和AfterViewChecked钩子的作用,尤其是在处理子组件视图变化时的响应策略,以及通过实例演示如何在确保单向数据流的同时触发重新渲染。学习如何在Angular应用中安全地进行视图更新。

被折叠的 条评论
为什么被折叠?



