簡體   English   中英

在 angular 中更新 innerHTML 代碼時如何檢測指令的變化?

[英]How to detect changes in a directive when innerHTML code is updated in angular?

我正在測試一個添加到 div 的指令,這些指令正在實現 innerHTML,該指令通過單擊 div(更改顏色)負責 highlingthing,但我想在組件更新 innerHTL 中的內容時進行更改同樣,問題是 ngOnChanges 掛鈎不知道任何更改。 如何處理指令中的這種變化? 什么事件更適合聽取這種變化? 需要主機監聽器嗎?

指令執行:

<div appHighlight [innerHTML]="htmlStr"></div>

指令中的更改

@Directive({
  selector: '[appHighlight]',
})
export class HighlightDirective implements OnInit, OnChanges {
  constructor(private el: ElementRef) {
     this.el.nativeElement.style.backgroundColor = 'yellow';
  }

  ngOnChanges(changes) {
   console.log('ngOnChanges ---->');
   console.log(changes, 'changes are not dectected');
   this.changeColor();
  }

  ngOnInit() {
     console.log('ngOnInit ---->');
  }

  @HostListener('click', ['$event.target'])
  onClick(btn) {
      this.changeColor();
  }

  changeColor() {
    this.el.nativeElement.style.backgroundColor = 'magenta';
  }
}

Stackblitz 示例:

div 中使用 innerHTML 的指令

@input發生變化時會發生變化檢測

這可能不是您想要的,而是您可以做的。

在您突出顯示的指令中添加一個輸入:

@Input()
htmlString: string; // this is the named you bind to -> [htmlString]

然后在指令上也應用綁定

<div appHighlight [htmlString]="htmlStr" [innerHTML]="htmlStr"></div>

然后你會得到更新。 當您更新字符串時,它會在稍后再次初始化時發生。

編輯過的曲目: https://stackblitz.com/edit/angular-ivy-xvr116?file=src%2Fapp%2Fdirectives%2Fhighlight.directive.ts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM