为什么 angular 不在动态创建的组件中填充视图?
Why angular does not populate view in dynamically created component?
我有一个使用第三方地图库的组件。 MousePositionComponent
在我的 MapModule
.
@Component({
....,
template: `<span>{{coordinate}}</span>`
})
export class MousePositionComponent implements OnInit {
public coordinate: string;
ngOnInit() {
this.map.on("click", this.onMapClicked());
}
private onMapClicked(): (evt: MapBrowserEvent) => void {
return (event: MapBrowserEvent) => {
let coordinate = this.transformCoordinate(event.coordinate);
this.coordinate = this.formatCoordinate(coordinate);
console.log(this.coordinate)
}
}
}
所以我在 ApplicationModule
中使用 MapModule
。如果我在动态创建的 SommeComponent
中使用,它会起作用。如果我有动态创建的 AnotherComponent
,视图不会更新,但 console.log(this.coordinate)
有效。
该函数在 Angular 区域之外执行,因此您需要明确地告诉它,以便 运行 对点击事件进行更改检测
constructor(private ngZone:NgZone){
}
ngOnInit() {
this.map.on("click", this.ngZone.run(()=>this.onMapClicked()));
}
private onMapClicked(): (evt: MapBrowserEvent) => void {
return (event: MapBrowserEvent) => {
let coordinate = this.transformCoordinate(event.coordinate);
this.coordinate = this.formatCoordinate(coordinate);
console.log(this.coordinate)
}
}
我有一个使用第三方地图库的组件。 MousePositionComponent
在我的 MapModule
.
@Component({
....,
template: `<span>{{coordinate}}</span>`
})
export class MousePositionComponent implements OnInit {
public coordinate: string;
ngOnInit() {
this.map.on("click", this.onMapClicked());
}
private onMapClicked(): (evt: MapBrowserEvent) => void {
return (event: MapBrowserEvent) => {
let coordinate = this.transformCoordinate(event.coordinate);
this.coordinate = this.formatCoordinate(coordinate);
console.log(this.coordinate)
}
}
}
所以我在 ApplicationModule
中使用 MapModule
。如果我在动态创建的 SommeComponent
中使用,它会起作用。如果我有动态创建的 AnotherComponent
,视图不会更新,但 console.log(this.coordinate)
有效。
该函数在 Angular 区域之外执行,因此您需要明确地告诉它,以便 运行 对点击事件进行更改检测
constructor(private ngZone:NgZone){
}
ngOnInit() {
this.map.on("click", this.ngZone.run(()=>this.onMapClicked()));
}
private onMapClicked(): (evt: MapBrowserEvent) => void {
return (event: MapBrowserEvent) => {
let coordinate = this.transformCoordinate(event.coordinate);
this.coordinate = this.formatCoordinate(coordinate);
console.log(this.coordinate)
}
}