Angular 2焦点指令问题

时间:2016-12-13 18:11:57

标签: angular angular2-directives

我正在尝试创建一个更新类型函数,我在其中选择一个编辑按钮,它侧重于要编辑的注释的描述。但是我不明白如何抓住我想要编辑的特定帖子的具体描述。这里有一些html和我想要实现的概念...

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

这是一个包含所有代码指令和所有https://plnkr.co/edit/HSuLScvffC0G5sfMHjJ5?p=preview

的plunker

我愿意接受我可能以错误的方式接近这一点。任何方向都会非常感激。

1 个答案:

答案 0 :(得分:1)

我认为网络组件的强大功能可以解决问题。改为创建一个注释组件并将编辑逻辑封装在那里:

<强> 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();
  }
}

这里有一名工作人员:https://plnkr.co/edit/G8s8tw2R2zyrJaD1NGW0?p=preview