ngModel is not working on <div> tag using contenteditable and have html as an input

穿精又带淫゛_ 提交于 2021-02-19 08:04:13

问题


I am trying to bind my input, which is string having html content in it. app.component.ts has 'content' variable

content : string = "<p>This is my editable data.</p><p>Two way binding is   not getting applied on it.</p>
public validateProfile(content){
console.log(content);
}

app.component.html has following code

<div contentEditable="true" [innerHTML]="content" [(ngModel)]="content"></div>
  <button type="submit" class="btn btn-info" (click)="validateProfile(content)">Validate Profile</button> 

I am able to edit the content inside tag. As my input is html data in string format , I can't bind it to input tag. Can someone please suggest how to apply 2 way binding with contenteditable= true on div or span.


回答1:


Try like this :

template

<div contenteditable="true" [innerHTML]="content" (input)="contentNew=$event.target.textContent"></div>
<br/>
<button type="submit" class="btn btn-info" (click)="validateProfile(contentNew)">Validate Profile</button>

typescript

  contentNew: string;
  content : string = "<p>This is my editable data.</p><p>Two way binding is   not getting applied on it.</p>";

  public validateProfile(content){
    this.contentNew = content;
    console.log(content);
  }

demo




回答2:


To bind with a value do this

<div contenteditable=true (input)="content= $event.target.innerHTML; htmlContentChange($event.target.innerHTML)" (contentChange)="someFunction()"></div>

In your component

export class myComponent {
    @Input() content;
    @Output() contentChange = new EventEmitter(); // for two way binding

   /*
   * update html on changes in content editable
   */
   htmlContentChange(value) {
      this.htmlChange.emit(value);
   }
}



回答3:


I tried the following way and its working fine. try it out

<input type="text" [(ngModel)]="content"/>
<div contentEditable="true" [(innerHTML)]="content" ></div>
<button type="submit" class="btn btn-info" (click)="validateProfile(content)">Validate Profile</button> 


来源:https://stackoverflow.com/questions/47093360/ngmodel-is-not-working-on-div-tag-using-contenteditable-and-have-html-as-an-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!