[英]Apply attribute directive on component in Angular 4
I have created img-pop component which has @Input()
bind property src. 我创建了img-pop组件,它具有
@Input()
绑定属性src。 I have created authSrc directive which has @HostBinding()
property src. 我创建了具有
@HostBinding()
属性src的authSrc指令。
@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;
}
}
I have directive like this. 我有这样的指示。
@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>
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'.
但它抛出
Can't bind to 'src' since it isn't a known property of 'img-pop'.
error 错误
Please correct me if i am wrong with conceptual. 如果我对概念错了,请纠正我。
Thank you. 谢谢。
According to this answer by the core contributor it's impossible to set direct properties of the component using @HostBinding
. 根据核心贡献者的回答 ,使用
@HostBinding
设置组件的直接属性是不可能的。 @HostBinding
always binds directly to the DOM. @HostBinding
总是直接绑定到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->";
}
}
Directives are only instantiated for selectors that match HTML which is added to components templates statically. 指令仅针对匹配HTML的选择器进行实例化,HTML将静态添加到组件模板中。
There is no way to add/remove directives from an element dynamically. 无法动态地从元素添加/删除指令。 The only way is to add/remove the whole element (for example using
*ngIf
唯一的方法是添加/删除整个元素(例如使用
*ngIf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.