angular - 在 Angular 4 的组件上应用属性指令

标签 angular angular2-directives angular-components angular2-hostbinding

我已经创建了具有 @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'. 错误

plnkr link

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

谢谢。

最佳答案

根据 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/

相关文章:

html - 我如何从 Angular 5.2 的 IFrame 中引用 CSS(从 SCSS 编译而来)?

javascript - 在 *ngFor 循环中仅检查一个复选框(单选按钮行为)

javascript - Angular 2 使用 *ngFor 和 ngIf 隐藏第一个元素

javascript - Angular 2 中多个元素的单击处理程序

无法读取 null 的属性 'loadChildren' 中的 Angular CLI 错误

angular - Cdk虚拟滚动问题

angular - 是否可以测试 Angular 2 中是否存在自定义指令属性?

angular - 如何在Angular Dart项目中将Material-icon颜色更改为angular_components的白色?

dart - 在 AngularDart 中的媒体更改时将应用程序布局抽屉持久更改为临时

angular - 如何在 Angular 5 中进行同步调用?