【问题标题】:Angular 2 Focus Directive IssuesAngular 2 焦点指令问题
【发布时间】:2016-12-13 18:11:57
【问题描述】:

我正在尝试创建一个更新类型的函数,我在其中选择一个编辑按钮,它专注于要编辑的评论的描述。但是,我不明白如何仅获取我要编辑的特定帖子的特定描述。这是一些 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

我愿意接受我可能以错误的方式处理这个问题。任何方向将不胜感激。

【问题讨论】:

  • 问题是您的isEditableinputFocused 变量是非歧视性的。
  • 是的,但是假设有 100 个 cmets,我不想创建 100 个布尔值来区分我要编辑的评论。有没有像this.comment.focus 这样的设置我可以做?
  • 不要手动创建它们,然后:plnkr.co/edit/YfIE66eO7W9lMabA52Ac?p=preview
  • @yurzui 太完美了!谢谢你。您能否发布一个答案来解释这是如何工作的?我想更好地理解它。

标签: angular angular2-directives


【解决方案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();
  }
}

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

【讨论】:

    猜你喜欢
    • 2018-01-27
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多