繁体   English   中英

为什么angular x ngStyle无法动态更新?

[英]Why angular x ngStyle does not update dynamically?

我不明白为什么这几行行不通。

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的style属性:none值。 很好,但是当我的脚本调用someFunc()时,样式值正在更改,但仅在ts中不更改DOM。

提前为您准备好时间。 :)


要求的详细信息(已重写)

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

date-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';
    }
  }
...

最近的工作流程

它应该工作

StackBlitz示例

使用消毒剂时,只有这种方式才能起作用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM