首页 > 解决方案 > 如何在跨度Angular2 +中绑定占位符

问题描述

我的情况我只想在跨度中绑定一个占位符。当我使用输入时它工作得很好,但我必须在可编辑的范围内进行

<span 
  #newComment 
  class="postcomment"
  contenteditable="true"
  [placeholder]="'Comment.Write'|translate"
  // it's working if I don't bind it like this : placeholder="your comment"
>
</span>

我的错误是:

Can't bind to 'placeholder' since it isn't a known property of 'span'

如果您有解决方案,谢谢。而且我不能使用输入:)

标签: angular

解决方案


正如评论者已经明确指出的那样,该属性对元素placeholder无效,即使具有该属性也是如此。<span>contenteditable

当您设置时contenteditable,在您设置的代码中,innerHTML或者innerText如果数据为空白,您可以注入一个占位符模板。然后,您需要绑定到焦点事件并在焦点输入和输出时清除/重新添加此模板。

如果您经常使用它,将它包装在指令中最适合您。一个简短的例子;

组件.ts 代码

comment = null; // When comment is null, the template will be shown
template = 'Please enter your comment...';

组件.html代码

<span
    #newComment
    (focusin)="comment = (comment === null ? '' : comment)"
    (focusout)="newComment.innerText.trim() === '' ? comment = null : comment = newComment.innerHTML"
    [innerHTML]="comment === null ? template : comment"
    contenteditable="true">
</span>

推荐阅读