为什么angular x ngStyle不会动态更新?

时间:2017-11-27 12:31:37

标签: angular dynamic ng-style

我不明白为什么这几行无效。

HTML模板:

<input class="picked-clear main-line-item main-line-box" type="button" value="" #pickedClear [ngStyle]="style" (click)="handleClearPickedBox($event)" />

component.ts: ...

export class DatePickerComponent implements OnInit, AfterViewInit {

  placeholder:string = "Select a date";
  style:any = {
    'background-image': "none"
  }

  @ViewChild('pickedBox') pickedBox;
  @ViewChild('pickedClear') pickedClear;

  constructor() { }
  ...


someFunc(){
  ...
  this.style['background-image']="url(assets/img/datePicker/clear.svg)";
  ...
}
...

问题如下:在开始时,按钮获取带有background-image:none值的style属性。这很好,但是当我的脚本调用someFunc()时,样式值正在改变,但是只在ts中的DOM中没有。

提前你的时间。 :)

要求的详细信息(重写)

日期picker.component.ts:

<div class="date-picker">
  <div class="main-line">
    <input class="picked-box main-line-item" type="text" placeholder="{{placeholder}}" value="" #pickedBox (focus)="handlePlaceholderFocus($event)" (blur)="handlePlaceholderBlur($event)" (keyup)="handlePickedBoxChange($event)" />
    <input class="picked-clear main-line-item main-line-box" type="button" value="" #pickedClear [ngStyle]="style" (click)="handleClearPickedBox($event)" />
    <input class="picker-toggle-btn main-line-item main-line-box" type="button" value="" />
  </div>
  <div class="picker-cont">

  </div>
</div>

日期picker.component.ts:

export class DatePickerComponent implements OnInit, AfterViewInit {

  placeholder:string = "Select a date";
  style:any;

  @ViewChild('pickedBox') pickedBox;
  @ViewChild('pickedClear') pickedClear;

  constructor(private sanitizer:DomSanitizer) { }

  ngOnInit() {
    this.style={};
    this.style['background-image']='none';
    this.style['cursor']='auto';
  }
...
handlePickedBoxChange(event){
    var target =          event.target || event.srcElement || event.currentTarget;
    if(target.value.length>0){
      //this.pickedClear.nativeElement.style.backgroundImage = "url(assets/img/datePicker/clear.svg)";
      //this.pickedClear.nativeElement.style.cursor = "pointer";
      if(this.style['cursor']!='pointer'){
        this.style['background-image']=this.sanitizer.bypassSecurityTrustStyle('url(assets/img/datePicker/clear.svg)');
        this.style['cursor']='pointer';
      }
    }else{
      //this.pickedClear.nativeElement.style.backgroundImage = "none";
      //this.pickedClear.nativeElement.style.cursor = "auto";
      this.style['background-image']='none';
      this.style['cursor']='auto';
    }
  }
...

recent workflow

1 个答案:

答案 0 :(得分:0)

应该有效

StackBlitz example

使用消毒剂,只有这种方式似乎有效:

<div [style.background-image]="backgroundImageSanitized">