问题
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