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

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

问题描述

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

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;
}

}

我有这样的指令.

@Directive({ selector: '[authSrc]' })
export class AuthSrcDirective implements OnInit {

@HostBinding()
private src: string;

constructor(private element: ElementRef) { }

ngOnInit() { }

  @Input()
  set authSrc(src) {
   this.src = src+"?access_token=<-token->";
  }
}

我想将两种功能结合在一起.

i want to combine both functionality in one like.

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

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

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

但是会引发Can't bind to 'src' since it isn't a known property of 'img-pop'.错误

plnkr链接

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

Please correct me if i am wrong with conceptual.

谢谢.

推荐答案

根据答案"不可能使用@HostBinding设置组件的直接属性. @HostBinding始终直接绑定到DOM.因此,这是设计使然.这是解释:

According to this answer by the core contributor it's impossible to set direct properties of the component using @HostBinding. @HostBinding always binds directly to the DOM. So this is by design. Here is the explanation:

这可以按预期工作,如:

This works as intended, as:

  • 使用数据绑定在以下指令/组件之间进行通信 同一个元素比直接沟通要慢, 注入其他数据
  • 指令之间的
  • 绑定很容易导致 周期.
  • using data binding to communicate between directives / components on the same element is slower than direct communication by making one inject the other data
  • binding between directives easily leads to cycles.

因此,在您的情况下,这是可能的解决方案:

So, in your case, this is the possible solution:

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天全站免登陆