@HostBinding 初始@Input 值被忽略

@HostBinding initial @Input value ignored

我有一个指令可以帮助向各种元素添加切换效果。

export class AlloyToggleDirective {
    private toggled = false;

    @Input('alloyToggled')
    @HostBinding('class.alloy-toggled')
    get isToggled() { return this.toggled; }
    set isToggled(value: boolean) {
      this.toggled = value;
      this.alloyToggledChange.emit(this.toggled);
    }
    @Output() alloyToggledChange: EventEmitter<boolean> = new EventEmitter();

    toggle() {
      this.toggled = !this.toggled;
    }

    @HostListener('click')
    onclick() {
        this.toggled = !this.toggled;
        this.alloyToggledChange.emit(this.toggled);
    }
}

切换时它工作正常,但是初始绑定值被忽略:

<button [alloyToggled]="booleanValue">

HTML 将反映该初始值,但 class 仅在以编程方式或通过鼠标切换后应用。当 @HostBinding@Input 上时是否有奇怪的交互?

有几个问题:

  • @输入定义

  • 可变语法混淆

directive.ts

@Directive({
  selector: '[alloyToggled]'
})
export class HighlightDirective {
    @Input('alloyToggled') alloyToggled: boolean;
    @HostBinding('class.alloy-toggled')
    get isToggled() { return this.alloyToggled; }
    set isToggled(value: boolean) {
      this.alloyToggled = value;
      this.alloyToggledChange.emit(this.alloyToggled);
    }
    @Output() alloyToggledChange: EventEmitter<boolean> = new EventEmitter();

    toggle() {
      this.alloyToggled = !this.alloyToggled;
    }

    @HostListener('click')
    onclick() {
        this.alloyToggled = !this.alloyToggled;
        this.alloyToggledChange.emit(this.alloyToggled);
    }
}

html

<button [alloyToggled]="booleanValue">Toggle Alloy</button>

component.ts

export class AppComponent {
  booleanValue = true;
}

已编辑 HighlightDirective 以反映您预期的代码行为。 https://stackblitz.com/edit/angular-lrmveu

根据 Angular 突出显示示例创建:https://stackblitz.com/angular/naavjopgege?file=src%2Fapp%2Fapp.component.html