Nav*_*raj 7 angular2-directives angular-components angular2-hostbinding angular
我创建了img-pop组件,它具有@Input()绑定属性src.我创建了authSrc指令,它具有@HostBinding()属性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;
}
}
Run Code Online (Sandbox Code Playgroud)
我有这样的指示.
@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->";
}
}
Run Code Online (Sandbox Code Playgroud)
我希望将两种功能结合在一起.
<img-pop [authSrc]="/api/url/to/image"></img-pop>
Run Code Online (Sandbox Code Playgroud)
所以最终的url调用将是/ api/url/to/image?access_token = < - token - >
但它会引发Can't bind to 'src' since it isn't a known property of 'img-pop'.错误
如果我对概念错了,请纠正我.
谢谢.
根据核心贡献者的回答,不可能使用@HostBinding. @HostBinding始终直接绑定到 DOM。所以这是设计使然。解释如下:
这按预期工作,如下所示:
- 使用数据绑定在同一元素上的指令/组件之间进行通信比通过注入另一数据的直接通信慢
- 指令之间的绑定很容易导致循环。
因此,对于您的情况,这是可能的解决方案:
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->";
}
}
Run Code Online (Sandbox Code Playgroud)
有关更通用的方法,请参阅此。
| 归档时间: |
|
| 查看次数: |
6560 次 |
| 最近记录: |