簡體   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