angular 如何在原生JS中調用angular組件內的方法

問題:在使用js插件的過程中,想再js插件觸發方法然後調用angular內部的方法;

解決方案:
將組件在全局映射中註冊,使用構造函數或ngOnInit()其他任何生命週期掛鉤來註冊組件並ngOnDestroy()取消註冊。以此來達到目的;

原理:從Angular外部調用Angular方法時,Angular無法識別模型更改。這就是Angulars的NgZone目的。要獲得對Angular區域的引用,只需將其注入構造函數

代碼:
1.構造函數內映射

export class MyComponent implements OnDestroy{
	constructor(zone:NgZone) {
		//映射註冊
	 	window['MyComponent'] = {component: this, zone: zone};
	}
	
	ngOnDestroy() {
		//映射註銷
        window['MyComponent'] = null;  
    }
	
	callFromOutside(){
		console.log('外部調用')}
}

2.外部調用

	//外部js調用
	window.MyComponent.component.callFromOutside();

這樣簡單的兩步,就完成了在外部函數中調用angualr內部的方法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章