Angular 15: получить данные из hostDirective в компоненте

Можно ли использовать API композиции директив для предоставления входных данных компоненту?

      @Directive({
  selector: '[colorConfig]',
})
class ColorConfigDirective() {
  @Input() colorName: string;
}

@Component({
  selector: 'my-icon',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './my-icon.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  hostDirectives: [ColorConfigDirective]
})
export class MyIconComponent {

  // How to get color passed to ColorConfigDirective here ??? Is it possible?

}

Прочитал документы, но не нашел ничего полезного

1 ответ

Использование в конструкторе компонента

      constructor(@Optional() @Host() private colorDirective:ColorConfigDirective){
     //you can check if null to give a default value
     if (this.colorDirective===null)
     {
          ...do something...
     }
}

Кстати, директива должна быть такой

      @Directive({
  selector: '[colorConfig]',
})
// see the "export" and it's not with ()
export class ColorConfigDirective {
  @Input() colorName: string;
  //See that you can use also the same name to the Input to not need add 
  //an auxiliar attribute
  @Input('colorConfig') config //<--in this case the name of variable is config
  //or
  @Input() colorConfig

}
Другие вопросы по тегам