我试图创建新的组件,但它的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)这是我的代码
@Component({
template: `<h1>Hello from A</h1>
<ul>
<li *ngFor="#letter of letters; #i = index">
<button (click)="appendW(i)">{{letter | uppercase}}</button>
</li>
</ul>
<button (click)="doSomething()">Click</button>`,
pipes: [UpperCasePipe],
directives: [NgFor]
})
export class AComponent {
letters = ['a','b','c','d'];
contructor(){
}
appendW(index) {
// console.log(letter);
setTimeout(()=>{
this.letters[index] += "W";
}, 1000)
}
...
}
Run Code Online (Sandbox Code Playgroud)
在setTimeout之后,对内容和视图进行两次角度检查.有人可以解释一下吗?为什么角度需要检查TWICE?