2016-12-13 114 views
-1

我正在嘗試創建一個更新類型函數,我選擇一個編輯按鈕,它將重點放在要編輯的註釋的描述上。但是,我不明白如何抓住我想編輯的特定帖子的具體描述。下面是一些HTML和我所試圖達到的概念...Angular 2 Focus Directive Issues

<div> 
     <p [contentEditable]="isEditable" [focus]="inputFocused">Test 1</p> 
     <button (click)="Edit()">edit 1</button> 
    </div> 
    <div> 
     <p [contentEditable]="isEditable" [focus]="inputFocused">Test 2</p> 
     <button (click)="Edit()">edit 2</button> 
    </div> 

,這裏是所有的代碼指令來接受我一個plunker和所有https://plnkr.co/edit/HSuLScvffC0G5sfMHjJ5?p=preview

我打開可能會以錯誤的方式接近。任何方向將不勝感激。

+0

問題是你的'isEditable'和'inputFocused'變量是非盤riminatory。 – silentsod

+0

是的,但說有100條評論,我不想創建100個布爾值來區分我想要編輯的評論。有沒有像我可以做的'this.comment.focus'類型的設置? – Bean0341

+1

檢查https://plnkr.co/edit/yrDLST1teuJCopnPafZR?p=preview – yurzui

回答

1

我認爲Web組件的力量可以幫助解決問題。創建註釋組件,而不是和封裝編輯邏輯有:

app.ts

//our root app component 
import {Component, NgModule} from '@angular/core' 
import {BrowserModule} from '@angular/platform-browser' 
import {MyComment} from './comment.component'; 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <ul *ngFor="let comment of comments"> 
     <li> 
      <my-comment [comment]="comment"></my-comment> 
     </li> 
     </ul> 
    </div> 
    `, 
}) 
export class App { 
private comments = ['Comment 1', 'Comment 2']; 
} 

@NgModule({ 
    imports: [BrowserModule], 
    declarations: [App, MyComment], 
    bootstrap: [App] 
}) 
export class AppModule {} 

comment.component.ts

import {Component, Input, ViewChild, OnInit} from '@angular/core' 

@Component({ 
    selector: 'my-comment', 
    template: ` 
    <div> 
     <p #text>{{comment}}</p> 
     <button (click)="Edit()">Edit</button> 
    </div> 
    `, 
}) 
export class MyComment { 
    @Input() comment: string; 
    @ViewChild('text') paragraph: HtmlElement; 

    Edit() { 
    let element = this.paragraph.nativeElement; 
    element.contentEditable = true; 
    element.focus(); 
    } 
} 

一個工作plunker這裏:https://plnkr.co/edit/G8s8tw2R2zyrJaD1NGW0?p=preview

+0

感謝您的回答Michael,@yurzui評論和plunkr正是我的應用程序已經建立。我回答了他的答案。你的回答也能正常工作,但需要在我的結尾做一點修改。 +1的努力謝謝你! – Bean0341

+0

沒問題,@ yurzi的解決方案也是一個不錯的方法。 –