我以前需要這樣的東西,所以我想我會分享我是如何解決這個問題的。
與OP類似,我需要免費觸發父組件中子組件的方法。我希望能夠在不使用$ onChanges生命週期鉤子的情況下自由/單獨地在父級中觸發此方法。
相反,我創建了一個通知註冊機制,允許子組件在加載時向父節點「註冊」方法。這個方法可以由$ onChanges週期外的父級自由觸發。
我創建了一個codepen來演示這一點。它可以很容易地擴展爲處理來自父級的與數據更改無關的不同類型的通知。
的Index.html
<div ng-app="tester">
<parent></parent>
</div>
的script.js
angular.module('tester', []);
angular.module('tester').component('parent', {
controller: parentController,
template: `
<div class="tester-style">
<button ng-click="$ctrl.notifyChild()">Notify child</button>
<child parent-to-child-notification-registration="$ctrl.childComponentNotificationRegistration(handler)">
</div>
`
});
function parentController() {
let childComponentEventHandler = null;
this.$onInit = function() {
this.value = 0;
};
this.childComponentNotificationRegistration = function(handler) {
childComponentEventHandler = handler;
console.log('Child component registered.');
};
this.notifyChild = function() {
if (childComponentEventHandler) {
childComponentEventHandler(this.value++);
}
};
}
angular.module('tester').component('child', {
bindings: {
parentToChildNotificationRegistration: '&',
},
controller: childController,
template: `
<div class="tester-style">
<h4>Child Component</h4>
</div>
`
});
function childController() {
this.$onInit = function() {
this.parentToChildNotificationRegistration({
handler: this.processParentNotification
});
};
this.processParentNotification= function(parentValue) {
console.log('Parent triggered child notification handler!!!');
console.log('Value passed to handler:', parentValue);
};
};
}
也爲類似@adam0101的#3回答的東西看codepen。
請添加組件定義。 – alphapilgrim
Components = https://docs.angularjs.org/guide/component – TkNeo
不,我的意思是你的代碼,你的組件。不是什麼組件的定義。實際的JS部分。 – alphapilgrim