解决方法很简单,我们需要在Directive中更新更新我们的值,就要用到implements OnChanges。并在ngOnChanges方法中实现@HostBinding值的变化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import { Directive, HostBinding, Input,OnChanges,Renderer2, SimpleChanges } from '@angular/core'; @Directive({ selector: '[appFavbuttonwidth]' }) export class FavbuttonwidthDirective implements OnChanges { @HostBinding('style.width') width: string; @Input('buttonstate') paystate: boolean; constructor(private renderer2: Renderer2 ) { } ngOnChanges(changes: SimpleChanges): void { this.widthchanage() } ngOnInit(): void { this.widthchanage() } widthchanage(){ if(this.buttonstate == true){ this.width = '25%' } if(this.buttonstate == false){ this.width = '50%' } } } |
来看看component如何使用
HTML文件
1 |
<div class="submit" appFavbuttonwidth [buttonstate]="widthchange()"> |
TS文件
1 2 3 4 5 6 |
widthchange(){ if(this.cate == '1'){ return true; } return false } |
大功告成!