1

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

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 将反映该初始值,但该类仅在以编程方式或通过鼠标切换后应用。@HostBinding开启时是否有奇怪的交互@Input

4

1 回答 1

1

有几个问题:

  • @输入定义

  • 变量语法混淆

指令.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>

组件.ts

export class AppComponent {
  booleanValue = true;
}

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

从 Angular Highlight 示例创建:https ://stackblitz.com/angular/naavjopgege?file=src%2Fapp%2Fapp.component.html

于 2020-02-07T21:32:57.817 回答