在Angular 4中对组件应用属性指令

时间:2017-05-15 14:19:06

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

我创建了img-pop组件,它具有@Input()绑定属性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;
}

}

我有这样的指示。

@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>

这样最终的网址调用将是/ api / url / to / image?access_token =&lt; - token - &gt;

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

plnkr link

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

谢谢。

2 个答案:

答案 0 :(得分:2)

根据核心贡献者的this answer,使用@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->";
    }
}

有关更通用的方法,请参阅this

答案 1 :(得分:1)

指令仅针对匹配HTML的选择器进行实例化,HTML将静态添加到组件模板中 无法动态地从元素添加/删除指令。唯一的方法是添加/删除整个元素(例如使用act = tf.nn.relu(conv + b) tf.nn.max_pool()