peco123
peco123

Reputation: 87

How can i change property value of specific directive reference from another directive

I have created directive where on click of button i change it's property value status.

{{ tempDirOne.status }}
<button appDirOne #tempDirOne="appDirOne">Diritive One first btn</button>

{{ tempDirTwo.status }}
<button appDirOne #tempDirTwo="appDirOne">Diritive One second btn</button>

DIRECTIVE ONE

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[appDirOne]',
  exportAs: 'appDirOne'
})
export class DirOneDirective {
  status: boolean = false;
  constructor() { }

  @HostListener('click') onClick() {
    this.status = !this.status;
  }

}

so i have two different references tempDirOne and tempDirTwo.

Now i have another directive where when it's element is clicked i need to change the status property of the first directive.

<button appDirTwo #tempDurSecondDirective="appDirTwo">Directive two button</button>

THE SECOND DIRECTIVE

@Directive({
  selector: '[appDirTwo]',
  exportAs: 'appDirTwo'
})
export class DirTwoDirective {

  constructor() { }

  @HostListener('click') onClick() {
    // change hier the status property of directive one - but
    // because there are two instances - change manually eiter on tempDirOne or tempDirTwo
  }

}

Upvotes: 0

Views: 484

Answers (1)

MBB
MBB

Reputation: 1685

In angular you can get the reference of the another directive if both the directives on the same element.

But, in your case both the directives are in different elements and you cannot directly refer an instance of another directive.

To fulfil the requirement you could use services to update the status. In this approach you need to modify the component html to have another property type to differentiate between the two directive instances.

Below is the sample snippet for the same.

https://stackblitz.com/edit/angular-ivy-qbejij?file=src%2Fapp%2Fapp.component.html

Upvotes: 2

Related Questions