Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
900 views
in Technique[技术] by (71.8m points)

typescript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...