【发布时间】:2021-02-25 00:22:56
【问题描述】:
我正在使用角度应用程序,我发现角度生命周期事件是在没有实现接口的情况下调用的。在下面的示例中,如果我从组件中删除接口,那么所有角度生命周期钩子都可以正常工作。 关于没有实现接口的问题,为什么 Angular 会调用所有事件?
我知道在 typescript 中我们可以使用所有可以在 c# 中使用的 OOP 概念。
生命周期.component.ts
import {
Component,
OnInit,
OnChanges,
SimpleChanges,
Input,
AfterViewInit,
DoCheck,
AfterViewChecked,
AfterContentChecked,
AfterContentInit,
OnDestroy
} from '@angular/core';
@Component({
selector: 'app-life-cycle',
templateUrl: './life-cycle.component.html',
styleUrls: ['./life-cycle.component.css']
})
export class LifeCycleComponent
implements
OnChanges,
OnInit,
DoCheck,
AfterViewInit,
AfterViewChecked,
AfterContentChecked,
AfterContentInit,
OnDestroy {
@Input('appTitle') appTitle: string;
constructor() {
console.log('constructor called!');
}
ngOnChanges(changes: SimpleChanges) {
console.log('ngOnChanges called!');
console.log(changes);
}
ngOnInit() {
console.log('ngOnInit called!');
}
ngDoCheck() {
console.log('ngDoCheck called!');
}
ngAfterViewInit() {
console.log('ngAfterViewInit called!');
}
ngAfterViewChecked() {
console.log('ngAfterViewChecked called!');
}
ngAfterContentInit() {
console.log('ngAfterContentInit called!');
}
ngAfterContentChecked() {
console.log('ngAfterContentChecked called!');
}
ngOnDestroy() {
//console.log('ngOnDestroy called!');
}
}
生命周期.component.html
<p>
life-cycle works!
</p>
【问题讨论】:
-
谁反对我的问题?发表评论并投反对票。
-
接口是可选的。向 TypeScript 指令类添加接口是一种很好的做法,以便从强类型和编辑器工具中受益。
标签: angular typescript