2016-08-18 2 views
10

각도 2 어떻게 contentedit div로 양방향 데이터 바인딩을 할 수 있습니까?각도 2 contenteditable

<div class="editable" contenteditable="true"> 
    <h1>Text Field</h1> 
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In pharetra felis in sem porta feugiat.</p> 
</div> 
+0

[angle2에서 div의 contenteditable에 \ [(ngModel) \]을 어떻게 사용합니까?] (http://stackoverflow.com/questions/35378087/how-to-use-ngmodel-on-divs-contenteditable) -in-angular2) – tobek

답변

0

이 코드를 참조하십시오. 내가 생각하기에 잘 될거야. 내가 당신을 위해 링크를 볼 수있는 별도의 입력의

import {Directive, ElementRef, Input, Output} from "angular2/core"; 
import {EventEmitter} from "angular2/src/facade/async"; 
import {OnChanges} from "angular2/core"; 
import {isPropertyUpdated} from "angular2/src/common/forms/directives/shared"; 

@Directive({ 
    selector: '[contenteditableModel]', 
    host: { 
     '(blur)': 'onBlur()' 
    } 
}) 
export class ContenteditableModel implements OnChanges { 
    @Input('contenteditableModel') model: any; 
    @Output('contenteditableModelChange') update = new EventEmitter(); 

    private lastViewModel: any; 


    constructor(private elRef: ElementRef) { 
    } 

    ngOnChanges(changes) { 
     if (isPropertyUpdated(changes, this.lastViewModel)) { 
      this.lastViewModel = this.model 
      this.refreshView() 
     } 
    } 

    onBlur() { 
     var value = this.elRef.nativeElement.innerText 
     this.lastViewModel = value 
     this.update.emit(value) 
    } 

    private refreshView() { 
     this.elRef.nativeElement.innerText = this.model 
    } 
} 

:

@Component({ 
    selector: 'test-component' 
}) 
@View({ 
    directives: [ContenteditableModel] 
    template: ` 
     <h1 contenteditable="true" [(contenteditableModel)]="someObj.someProperty"></h1> 
     {{someObj | json}} 
    ` 
}) 
export class TestCmp { 
    someObj = {someProperty: "startValue"} 
} 

contenteditableModel.ts을 app.ts. https://www.namekdev.net/2016/01/two-way-binding-to-contenteditable-element-in-angular-2/

+0

고마워요! 당신은 코드 작품이지만 두 가지 문제가 있습니다 : -my someObj.someProperty에는 많은 html (10-15 태그)가 포함되어 있습니다. 4, "ID" [ { "어두워"여기 내 JSON 객체의 일부입니다 Summernote - 내가 뭔가를 수정 한 후 전체 HTML 내가 텍스트 편집기를 사용하여 텍스트를 편집 -to 일반 텍스트 된다 : 1, "moduleType": { "ID": 1, "이름": "텍스트 모듈", "내용": "

텍스트 필드 1

로렘 입숨 슬픔이, AMET consectetur의 adipiscing의 ELIT 앉아합니다. 전화 번호 :

" } }, moduleType.conten 내가 편집하고 싶은 것입니다. –

+0

ok. 나는 그것을 돌볼 것이다. :) –

11

저는 Isetty의 답변을 Angular 2.0의 릴리스 버전으로 적용했습니다. 이제는 사용할 수 있습니다. 릴리스 버전을 사용하는 것 외에도 innerText 대신 keyup 이벤트를 추가하고 textContent를 사용했습니다. 이는 내 애플리케이션을 더 잘 제공하기 때문입니다. 이러한 것들을 바꿀 수도 있습니다. 동적 편집과

import {Directive, ElementRef, Input, Output, EventEmitter, OnChanges} from "@angular/core"; 

@Directive({ 
    selector: '[contenteditableModel]', 
    host: { 
     '(blur)': 'onEdit()', 
     '(keyup)': 'onEdit()' 
    } 
}) 

export class ContentEditableDirective implements OnChanges { 
    @Input('contenteditableModel') model: any; 
    @Output('contenteditableModelChange') update = new EventEmitter(); 

    constructor(
     private elementRef: ElementRef 
    ) { 
     console.log('ContentEditableDirective.constructor'); 
    } 

    ngOnChanges(changes) { 
     console.log('ContentEditableDirective.ngOnChanges'); 
     console.log(changes); 
     if (changes.model.isFirstChange()) 
      this.refreshView(); 
    } 

    onEdit() { 
     console.log('ContentEditableDirective.onEdit'); 
     var value = this.elementRef.nativeElement.innerText 
     this.update.emit(value) 
    } 

    private refreshView() { 
     console.log('ContentEditableDirective.refreshView'); 
     this.elementRef.nativeElement.textContent = this.model 
    } 
} 
+0

David는 혹시라도 작업용 버전을 가지고 플 런커를 얻었습니까? –

+2

TSLint의 기본 호환 버전을 시도했지만 no-input-rename과 no-output-rename을 수정하는 솔루션이 없습니다. 다음을 참조하십시오 : https://gist.github.com/zamber/f2d15337c245285d498d9a6b94de3117 나는 받아들이 기 위해 들어가기, esc를 눌러 취소하기, 그리고 모든 keydown이 아닌 전체 가치 변화에 대해 밝히는 것과 같은 멋진 것들을 추가했습니다. – zamber

-1

각도 4/2 (타이프) :

// Imports 
import { Component} from '@angular/core'; 

@Component({ 
    selector: 'discussion', 
    template: `         
    <div class="details"> 
     <p class="time">Wednesday 14 Nov, 2016 10.13PM</p> 
     <p class="text" name="discussion" 
      [contentEditable]="editable" 
      [ngClass]="{ 'editable': editable }" 
      (blur)="uDiscussion()" 
      (click)="eDiscussion($event)" 
      (input)="discussion = $event.target.innerText" 
     >{{ discussion }}</p> 
    </div> 
    <div class="dropdown"> 
     <a href="#" data-toggle="dropdown" class="dropdown-toggle"> 
      <i class="fa fa-ellipsis-v"></i> 
     </a> 
     <ul class="dropdown-menu"> 
      <li><a (click)="eDiscussion($event)" >Edit</a></li> 
      <li><a (click)="dDiscussion()" >Delete</a></li> 
     </ul> 
    </div>`, 
    styles: [`.editable { 
     white-space: pre-wrap; 
     border: 1px solid coral; 
     width: 200px; 
     min-height: 20px; 
    }`] 
}) 

export class DiscussionComponent { 

    constructor(){} 

    public discussion: string = "Test string"; 
    public editable: boolean = false; 

    dDiscussion(){ 
     console.log("delete"); 
    } 

    eDiscussion(event: any){ 
     // on click this will set 'contentEditable' to true 
     // and add 'editable' class for styling. 
     this.editable = true; 
    } 

    uDiscussion(event: any){ 
     // on blur set 'contentEditable' to false 
     // and remove class 'editable' and log new values 
     this.editable = false; 
     console.log("this.discussion"); 
     console.log(this.discussion); 
    } 

} 
0

가 제대로 작동하려면, 지시 contenteditable에 대한 ControlValueAccessor을 구현하는 것이 필요하다. 내 솔루션 참조 : ng-contenteditable.