angular - 直接设置属性时不会触发 ngOnChanges
问题描述
我使用了 ng-bootstrap 的模态
在我的父组件中,我曾经modalService
打开模式,并使用componentInstance
.
在模态组件中,我用来ngOnChanges
获取我发送的数据。但未ngOnChanges
触发。
父组件
public toAttach(): void {
let modalRef = this.modalService.open(HelloComponent);
modalRef.componentInstance.attachments = this.attachments;
}
模态分量
ngOnChanges(changes: SimpleChanges) {
console.log("start!");
if (changes["attachments"] && changes["attachments"].currentValue) {
console.log(changes["attachments"].currentValue);
}
}
解决方案
当您直接设置组件实例的值时,它不会触发 ngOnChanges。ngOnChanges 在组件的值绑定发生更改时触发。它还取决于更改检测策略。如果您想直接更改组件实例变量的值,可以使用 setter 方法,在该方法中您可以在 ngOnChanges 中执行您想要执行的操作。例如 -
import {
Component,
Input,
AfterViewInit,
ChangeDetectorRef,
SimpleChanges,
OnChanges
} from "@angular/core";
@Component({
selector: "hello",
templateUrl: "./hello.component.html"
})
export class HelloComponent implements AfterViewInit, OnChanges {
@Input()
public attachments: any[];
constructor(private cd: ChangeDetectorRef) {}
ngAfterViewInit() {
this.cd.detectChanges();
}
setAttachments(attachments: []) {
this.attachments = attachments.slice();
// => DO YOUR WORK HERE
// Like calling change detection.
}
ngOnChanges(changes: SimpleChanges) {
console.log("start!");
if (changes["attachments"] && changes["attachments"].currentValue) {
console.log(changes["attachments"].currentValue);
}
}
}
在父组件中,调用
public toAttach(): void {
let modalRef = this.modalService.open(HelloComponent);
modalRef.componentInstance.setAttachments(this.attachments);
}
推荐阅读
- elixir - Elixir - 为什么这些重复的头文件没有编译器警告?
- android - Android Studio 的相同项目中不显示布局
- sql - 这两个字符串有什么区别?
- java - 使用 Java.net 的 Http 功能验证和发送请求
- java - MapStruc lib 的@Mapper(componentModel = "spring") 用于自动接口实现错误
- html - 如何在 django 的 html 模板中显示搜索查询的数据?
- angular - 带有路由选项卡的 Angular Material Routed 对话框
- qt - 无法覆盖 Qt QML 表单实现中的属性/实现处理程序
- foursquare - Foursquare API:如何在“自治市镇”等行政区域内探索场地
- laravel - 有没有办法通过命令行在 laravel 中制作服务容器文件?