在 Angular 4 中的组件上应用属性指令 [英] Apply attribute directive on component in Angular 4

查看:47
本文介绍了在 Angular 4 中的组件上应用属性指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了具有 @Input() 绑定属性 src 的 img-pop 组件.我创建了 authSrc 指令,它具有 @HostBinding() 属性 src.

I have created img-pop component which has @Input() bind property src. I have created authSrc directive which has @HostBinding() property src.

@Component({
selector: 'img-pop',

template: `<img [src]="src"/>
            <div *ngIf="isShow">
                 <----extra value----->
            </div>`
})

export class ImgPopOverComponent implements OnInit {

@Input()
private src;

private isShow=false;

@HostListener('mouseenter') onMouseEnter() {
    this.isShow= true;
}

@HostListener('mouseleave') onMouseLeave() {
    this.isShow= false;
}

}

`})导出类 ImgPopOverComponent 实现 OnInit {@输入()私有源代码;私人 isShow=false;@HostListener('mouseenter') onMouseEnter() {this.isShow=真;}@HostListener('mouseleave') onMouseLeave() {this.isShow=假;}}

I have directive like this.

我有这样的指令.

i want to combine both functionality in one like.

我想将这两种功能合二为一.

<img-pop [authSrc]="/api/url/to/image"></img-pop>

so that final url call will be /api/url/to/image?access_token= <--token-->

这样最终的 url 调用将是/api/url/to/image?access_token= <--token-->

but it throws Can't bind to 'src' since it isn't a known property of 'img-pop'. error

但它抛出无法绑定到'src',因为它不是'img-pop'的已知属性.错误

plnkr 链接

如果我在概念上有错误,请纠正我.

Thank you.

谢谢.

推荐答案

根据 this answer 核心贡献者不可能使用 @HostBinding 设置组件的直接属性.@HostBinding 总是直接绑定到 DOM.所以这是设计使然.解释如下:

This works as intended, as:

这按预期工作,因为:

  • 使用数据绑定在指令/组件之间进行通信同一个元素比直接通信慢注入其他数据
  • 指令之间的绑定很容易导致循环.

因此,就您而言,这是可能的解决方案:

export class AuthSrcDirective { // inject host component constructor(private c: ImgPopOverComponent ) { } @Input() set authSrc(src) { // write the property directly this.c.src = src + "?access_token=<-token->"; } }

For a more generic approach, see this.

这篇关于在 Angular 4 中的组件上应用属性指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆