Johannes Schacht
Johannes Schacht

Reputation: 1364

Two directives with same input binding

I have two directives with the same property binding, resulting in a name conflict.

<p appBorder color="red" appBackground color="yellow">Hello World!</p>

In this case, border and background are both yellow.

Of course, I can rename one of the Input() bindings. But in a large project with many independent programmers or bringing together code from different projects, this does not seem ideal. Is there a way to specify, which property belongs to which directive? E.g. appborder.color="red.

Upvotes: 0

Views: 792

Answers (1)

Mr. Stash
Mr. Stash

Reputation: 3160

You can pass values to attribute directive directly

<p [appBorder]="'red'" [appBackground]="'yellow'">Hello World!</p>

to do this you will have to add an input decorator in the directives with the same name as the directive

@Directive({
  selector: '[appBorder]',
})
export class BorderDirective implements OnInit, OnDestroy {
  @Input() set appBorder(color: string) {
    this.color = color
  }
  @Input() private color: string = '';
  ...
}

@Directive({
  selector: '[appBackground]',
})
export class BackgroundDirective implements OnInit, OnDestroy {
  @Input() set appBackground(color: string) {
    this.color = color
  }
  @Input() private color: string = '';
  ...
}

https://angular.io/guide/attribute-directives#passing-values-into-an-attribute-directive

Upvotes: 1

Related Questions