skip to Main Content

For example, I want to access the method tree.removenode via the chartContext in angular but I can’t seem to wrap my head around this.

enter image description here

3

Answers


  1. You use bracket notation:

    const something = theObject["the.property"];
    
    // or if it's a method
    
    const something = theObject["the.property"]();
    

    See MDN’s page on property accessors for more info

    Login or Signup to reply.
  2. If you are passing the method name as a string in variable you can do something like below:

    Suppose

    treeVar = 'tree';
    method = 'removenode';
    

    First check if its function or not

    if(typeof chartContext[treeVar][method] === 'function')
    

    Then,

    chartContext[treeVar][method]();
    
    Login or Signup to reply.
  3. To access a property or method with a dot (.) in its name in JavaScript, you can use bracket notation instead of dot notation. Here’s an example of how you can access the method tree.removenode using bracket notation:

    chartContext['tree.removenode']();
    

    In Angular, if chartContext is a property or variable in your component, you can use the same bracket notation to access the method:

    (chartContext as any)['tree.removenode']();
    

    By casting chartContext as any, you can bypass TypeScript’s type checking and access the property/method using bracket notation.

    Please note that accessing properties or methods with dots in their names is not recommended unless it’s absolutely necessary. It can make your code harder to read and maintain. If possible, consider refactoring the code to use a different naming convention or structure that doesn’t rely on dots in property/method names.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search