Angular ngOnInit默认提供生命周期钩子.
ngOnInit如果我们已经有了,为什么要使用constructor?
我试图创建新的组件,但它的ngOnInit()方法被调用两次,我不知道为什么会发生这种情况?这里我创建了一个名为ResultComponent的组件,它从名为mcq-component的父组件中获取@Input. 这是代码:
父组件(MCQComponent)
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'mcq-component',
template: `
<div *ngIf = 'isQuestionView'>
.....
</div>
<result-comp *ngIf = '!isQuestionView' [answers] = 'ansArray'><result-comp>
`,
styles: [
`
....
`
],
providers: [AppService],
directives: [SelectableDirective, ResultComponent]
})
export class MCQComponent implements OnInit{
private ansArray:Array<any> = [];
....
constructor(private appService: AppService){}
....
}
Run Code Online (Sandbox Code Playgroud)
子组件(result-comp)
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector:'result-comp',
template: `
<h2>Result page:</h2>
` …Run Code Online (Sandbox Code Playgroud)