首页 > 解决方案 > How to pass function as data to another module component in angular?

问题描述

I have a main module with some content and Nav

I have sub modules (lazy loaded) within the main module which should be giving me the nav Items.

I have made a service to pass data:

const navItems = [  
  { text: 'Add', icon: faUser,, function: 'AddDLevels()'},
  { text: 'Create D1', icon: faUser, function: 'toggleCreateD1()'},
  { text: 'Create D2', icon: faUser, function: 'toggleCreateD2()'},
  { text: 'Push DS78', icon: faUser, function: 'pushDS()'}
];
this.consoleNav.setNavItems(navItems);

How do I make the functions work ? I want to click the nav button and it should reflect in child modules component.

标签: angularangular9

解决方案


Rather than passing the functions as strings, you should pass a reference to a function, Eg:

const navItems = [  
  { text: 'Add', icon: faUser, function: () => AddDLevels()},
];

Then you just call that function in your on click handler or whatnot

item.function()

推荐阅读