【问题标题】:ViewChild can't pull directive from buttonViewChild 无法从按钮中提取指令
【发布时间】:2020-03-07 09:45:55
【问题描述】:

<button alloy #initialFocus></button>

通过以下方式访问时:


    ngOnInit(): void {
      this.initalFocusButton.focus();  // undefined unless it's an ElementRef
    }

在 OnInit 和 AfterViewInit 中出现 undefined(ng8 所以没关系)。我尝试了read 和选择器的各种组合,但它只能作为ElementRef 进行查询。在原生元素上查询指令是否有限制?

AlloyButtonDirective:

@Directive({
    selector: `button [alloy]`
})
export class AlloyButtonDirective implements AfterViewInit, OnDestroy {
    private unsubscribe = new Subject();

    // Default mode: Standard
    private currentStyle = Styles.Standard;

    @HostBinding(`class.alloy-button-standard`) @Input('standard')
    get isStandard() { return this.currentStyle === Styles.Standard; }
    set isStandard(value: any) {
        if (value !== false) {
            this.currentStyle = Styles.Standard;
        }
    }
    // More styles and a focus monitor.
    ...

【问题讨论】:

    标签: angular directive viewchild


    【解决方案1】:

    可能指令没有作为指令被拾取 - 所以它只是另一个 HTML 属性。给它添加默认构造函数并检查它是否被调用。

    【讨论】:

    • 样式应用于元素,因此构造了指令,但默认情况下它不是指令,如果我尝试read 指令,它是未定义的。
    • 您可以尝试提供stackblitz示例,一定会有人帮助您。
    猜你喜欢
    • 2017-09-02
    • 2015-09-27
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    相关资源
    最近更新 更多