如何检测角度为2的div中的内部html更改

如何检测角度为2的div中的内部html更改

本文介绍了如何检测角度为2的div中的内部html更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似

@Component({
  selector: 'my-component',
  template: '<div id="myDiv">Some value comes here dynamically from server</div>',
})
class MyComponent implements OnInit {
@Input()

  ngOnInit() {
      //execute my function when a content change is occured in #myDiv
  });
 }
}

如果"#myDiv"中发生了内容更改,我想执行一个功能.如何实现此功能?我还尝试了角度的(change)事件.

And if a content change has occurred in "#myDiv" I want to execute a function.How can I achieve this functionality?I also tried the (change) event in angular.

推荐答案

虽然看起来很简单,但是可以使用子组件以及Input,Output变量来实现.

Though it looks to be a simple one, but it can be achieved using child component and Input, Output variables.

用于显示服务内容的子组件

Child Component for displaying the content from the service

@Component({
  selector: 'title',
  template: `
    <div> {{title}}</div>
  `,
})
export class TitleComponent implements ngOnChanges{

  @Input() title:string="";
  @Output() titleChanged:EventEmitter<string>=new EventEmitter<string>();
  constructor(){
  //service call goes here
  }
  ngOnChanges(){
  console.log(this.val);
  this.titleChanged.emit(this.title);
  }

}

父组件将为

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <title (titleChanged)="changedTitle($event)" [title]="title"></title>
    </div>
  `,
})
export class App {
  name:string;
  title:string="some title";
  val:string;
  constructor() {
    this.val="";

  }

   changedTitle(va){
    console.log(va);

  }
}

说明:

  1. 拨打服务电话并更改标题值时.
  2. 更改输入属性后,会自动触发ngOnChanges.
  3. titleChanged 是Output()变量,并且在执行ngOnChanges时会发出一个值.
  4. 触发titleChanged时,将执行 changedTitle()中的关联方法.
  1. When service call is made and the title value gets changed.
  2. On change of the input property the ngOnChanges will be triggered automatically.
  3. The titleChanged is Output() variable and emits a value when ever ngOnChanges is executed.
  4. When the titleChanged is triggered, the associated method in the changedTitle() will be executed.

实时演示

LIVE DEMO

注意:为了显示此方法的有效性,我使用了一个文本框并将其分配给div元素.

Note: In order to show this is working I have used an text box and assigning it to the div element.

这篇关于如何检测角度为2的div中的内部html更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 20:45