gpt4 book ai didi

javascript - Angular2 从应用程序外部调用公开方法并丢失更改绑定(bind)

转载 作者:搜寻专家 更新时间:2023-10-30 21:41:15 25 4
gpt4 key购买 nike

我有一个公开给 window 的公共(public)方法。此方法与 Component 对话并修改我在模板中观察的变量。但是当我更改值时,*ngIf() 不会被触发。

应用组件

constructor(private _public: PublicService,) {
window.angular = {methods: this._public};
}

公共(public)服务

export class PublicService {

constructor(
private _viewManager: ViewManagerComponent,
) {}

CallMe(){
this._viewManager.renderView('page1')
}
}

布局管理组件

@Component({
selector: 'view-manager',
template: `<page *ngIf="view == 'page1'"></page>`
})
export class ViewManagerComponent {
//This is the variable being watched
view = "page";

renderView = function(type){
console.log(type)
this.view = type;
console.log(this.view)
};
}

所以想法是,当 View 最初加载时, View 是空白的。然后,当我键入 angular.methods.CallMe() 时,它会将 view 变量修改为 page1,然后它应该显示组件的 html。如果我控制 renderView 函数它被成功调用,只是 View 没有改变。

-----更新 - 仍然无法正常工作--------

export class ViewManagerComponent {
constructor(private zone:NgZone,private cdRef:ChangeDetectorRef) {

}
view = "page";

@Output() renderView(type){
// type is 'page'
console.log(this.view)
this.zone.run(() => {
// type is 'page'
console.log(this.view)
this.view = type;
// type is 'page1'
console.log(this.view)
});
// type is 'page1'
console.log(this.view)
//cdRef errors:
//view-manager.component.ts:36 Uncaught TypeError: this.cdRef.detectChanges is not a function(…)
this.cdRef.detectChanges();
};

}

最佳答案

在这种情况下,Angular2 不知道它需要运行更改检测,因为更改是由在 Angulars 区域之外运行的代码引起的。

显式运行变化检测

contructor(private cdRef:ChangeDetectorRef) {}

someMethodCalledFromOutside() {
// code that changes properties in this component
this.cdRef.detectChanges();
}

显式运行修改 Angulars 区域内组件属性的代码

contructor(private zone:NgZone) {}

someMethodCalledFromOutside() {
this.zone.run(() => {
// code that changes properties in this component
});
}

zone 方法更适用于 //更改此组件属性的代码 不仅更改当前组件的属性,而且还会引起其他组件的更改(比如this.router.navigate(),调用其他组件方法的方法引用)因为zone.run()在Angulars zone中执行代码,而你不不需要在每个组件中明确处理更改检测,因为此调用可能会发生更改。

如果您使用 function(...) 而不是 () =>,您可能会在 this 中得到意想不到的行为Angular 组件中的代码。

有关更多详细信息,另请参阅我对类似问题的回答 Angular 2 - communication of typescript functions with external js libraries

更新

export class ViewManagerComponent {
constructor(private zone:NgZone,private cdRef:ChangeDetectorRef) {
self = this;
}
view = "page";

@Output() renderView(type){
// type is 'page'
console.log(self.view)
self.zone.run(() => {
// type is 'page'
console.log(self.view)
self.view = type;
// type is 'page1'
console.log(self.view)
});
// type is 'page1'
console.log(self.view)
self.cdRef.detectChanges();
};

}

关于javascript - Angular2 从应用程序外部调用公开方法并丢失更改绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39971029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com