Angular 在ngAfterViewChecked中调用detectChanges()
如果我调用Angular 在ngAfterViewChecked中调用detectChanges(),angular,angular-changedetection,Angular,Angular Changedetection,如果我调用ngafterview checked中的ChangeDetectorRef.detectChanges()会有问题吗 AppComponent @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { name = 'Angular ' + VERS
ngafterview checked
中的ChangeDetectorRef.detectChanges()
会有问题吗
AppComponent
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular ' + VERSION.major;
childName = 'Child';
constructor(private cd: ChangeDetectorRef) {}
ngAfterViewChecked() {
this.cd.detectChanges()
}
}
export class HelloComponent {
@Input() name: string;
constructor(private parent: AppComponent) {}
ngAfterViewInit() {
this.parent.name = "Not";
}
}
HelloComponent
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular ' + VERSION.major;
childName = 'Child';
constructor(private cd: ChangeDetectorRef) {}
ngAfterViewChecked() {
this.cd.detectChanges()
}
}
export class HelloComponent {
@Input() name: string;
constructor(private parent: AppComponent) {}
ngAfterViewInit() {
this.parent.name = "Not";
}
}
由于我在AfterViewInit
中从子组件修改父组件的属性,它将给出“表达式已更改…”错误。但是如果我要在父组件的“AfterViewChecked”中添加detectChanges()
,则错误将消失,因为更改总是被检测到
这种方法有问题吗
在开发模式下,无论如何都会调用两次更改检测,所以我不是也通过这样做在生产中启用它吗
编辑
我知道这种方法的替代方法,但实际上我很好奇这种方法的缺点。例如,如果它可能有问题或无限循环。这是一个黑客解决方案,它可能会中断线路,因为它可能是未定义的行为。角度文档建议使用
setTimeout
或类似方法
我喜欢@AshotAleqsanyan关于使用服务在父组件和子组件之间共享更改的建议。或者使用(changeName)
输出更改名称
检查此视图及其子视图。与“分离”结合使用可实施本地更改检测检查
您可以将您的财产存储在服务中,并在两个位置使用它?或者,您可以使用应添加到父组件属性的值从子组件发出输出事件