Search code examples
htmlangulartypescriptangular2-forms

How to get innerHTML of this dynamic div in my Angular 2 application?


<div *ngFor="let field of page.fields"> 
    <div #ce class="infills richtextbox textarea {{field.groupid}}" contentEditable="true"
        *ngIf="(field.fieldtype=='textarea' && field.isexpandable=='true')"
        id="{{field.id}}" name="{{field.id}}"
        [ngStyle]="{'position':'absolute','top':field.y+'px','left':field.x+'px',
                    'font-size':'12px','font-family':'Courier New','height':field.height+'px',
                    'width':field.width+'px','background':'#EEE'}" 
        [(ngModel)]="field.value" title="{{field.description}}"
        (dblclick)="openFullRTE(field.id)" (focusout)="getHTMLContent()">
    </div>
</div>

In ts part,

getHTMLContent() {
    console.log(this.ce.nativeElement.innerHTML);
  }

When I write anything in first div, respective innerHTML is consoled properly. Then if I write something in second div, console gets overridden by data of first div. Please suggest a way to get HTML content of individual fields and to console them separately.


Solution

  • <div *ngFor="let field of page.fields; let i=index"> 
    
      <div #ce class="infills ri...
    
            (focusout)="getHTMLContent(i)"
    
    class MyComponent {
      @ViewChildren('ce') ces:QueryList<ElementRef>;
    
      constructor(private elRef:ElementRef) {}
    
      getHtmlContent(i) {
        console.log(this.ces.toArray()[i].nativeElement.innerHTML);
      }
    }