如何从指令中为属性设置值 | Angular

How to set value for atribute from directive | Angular

我有 HTML 个组件 <p-calendar appLocalization="awdwa" [locale]="calendarUa"></p-calendar>

我有我的自定义指令 appLocalization。指令代码

@Directive({
    selector: '[appLocalization]'
})
export class LocalizationDirective implements AfterContentInit, OnInit {
    @Output() appLocalizationChange: any;
    @Input() public appLocalization: string;

    public constructor(
        private el: ElementRef) {
    }
    ngOnInit() {
        this.el.nativeElement.attributes.locale = calendarUa;
        console.log(this.el.nativeElement.attributes.locale);
    }
}

接下来指令a会知道我需要为属性locale设置什么数据。语言环境不是我的属性。它是p-calendar.

的一个属性

如您所见,我试图在我的指令中得到这个 - this.el.nativeElement.attributes.locale。但它是未定义的。在那里你可以看到元素的属性。我做不到 this.el.nativeElement.attributes.ng-reflect-locale = calendarUa; 因为这是控制台中的错误。如何从我的自定义指令中设置其他属性的值?

如果 p-calendar 是一个组件,它不是一个属性而是一个 @Input。您需要将其注入您的指令:

public constructor(
  @Inject(ThatPCalendarComponent) private readonly pCalendar: ThatPCalendarComponent) {
}

然后this.pCalendar.locale = whatever