Shafeeque S
Shafeeque S

Reputation: 2613

How can I detect the inner html change in a div with angular 2?

I have a component like

@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      
  });
 }
}

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.

Upvotes: 1

Views: 10691

Answers (1)

Aravind
Aravind

Reputation: 41571

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);
  } 

}

Parent component will be as

@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);

  }
}

Explanation:

  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

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

Upvotes: 4

Related Questions