我認爲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
問題是你的'isEditable'和'inputFocused'變量是非盤riminatory。 – silentsod
是的,但說有100條評論,我不想創建100個布爾值來區分我想要編輯的評論。有沒有像我可以做的'this.comment.focus'類型的設置? – Bean0341
檢查https://plnkr.co/edit/yrDLST1teuJCopnPafZR?p=preview – yurzui