我已经创建了具有 @Input()
绑定(bind)属性 src 的 img-pop 组件。
我创建了具有 @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;
}
}
我有这样的指令。
@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->";
}
}
我想将这两种功能合而为一。
<img-pop [authSrc]="/api/url/to/image"></img-pop>
这样最终的 url 调用将是/api/url/to/image?access_token= <--token-->
但它会抛出 Can't bind to 'src' since it isn't a known property of 'img-pop'.
错误
如果我在概念上有错误,请纠正我。
谢谢。
最佳答案
根据 this answer核心贡献者不可能使用 @HostBinding
设置组件的直接属性。 @HostBinding
总是直接绑定(bind)到 DOM。所以这是设计使然。解释如下:
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.
因此,对于您的情况,这是可能的解决方案:
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->";
}
}
有关更通用的方法,请参阅 this .
关于angular - 在 Angular 4 的组件上应用属性指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43981841/