【问题标题】:Angular2 Directive : get tag contentAngular2指令:获取标签内容
【发布时间】:2017-03-17 06:35:04
【问题描述】:

我正在尝试创建指令,如果计数超过某个特定值,则可以减少符号数。

例如如果字符串长度超过8,则将其剪切并在末尾添加...

'some string here'

应该变成

'some str...'

这是我目前所拥有的

import { Directive, ElementRef, Input, Renderer  } from '@angular/core';

@Directive({
    selector: '[textOverflowLimit]',
})
export class TextOverflowLimitDirective {
    constructor(el: ElementRef, renderer: Renderer) {
        console.log(el.nativeElement);
    }
}

所以,问题是获取当前内容长度

el.nativeElement 返回

<td _ngcontent-awg-3 textoverflowlimit>Here is some long string that I want to cut off</td>

我在尝试

el.nativeElement.innerHTML
el.nativeElement.innerText

还有很多其他的,但我无法获得

Here is some long string that I want to cut off

字符串,没有标签前缀,有什么想法吗?

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:
    @Directive({
        selector: '[textOverflowLimit]',
    })
    export class TextOverflowLimitDirective {
        constructor(private el: ElementRef, renderer: Renderer) {}
    
        ngAfterViewInit() {
            console.log(this.el.nativeElement.innerText);
        }
    }
    

    Plunker example

    【讨论】:

    • 我假设了很多,但它没有用。您可以尝试使用 Plunker 并尝试优化。
    • 不,你是对的,那是我在构造函数中有代码的时候。感谢您的提示。
    • 虽然问题很简单,但ngAfterViewInit/ngAfterContentInit 哪个更好?在当前情况下。
    • 我没有尝试过,但我猜一个指令 ngAfterViewInit 不会被调用,因为它没有视图。 ngAfterContentInit() 仅在代码依赖于嵌入内容时才需要。指令类似于带有template: '&lt;ng-content&gt;&lt;/ng-content&gt;' 的组件,因此ngAfterContentInit 似乎合适。
    • ngAfterContent**Checked**()被调用plnkr.co/edit/xDpt37RbxDN6zVI0QiRY?p=preview时绑定被解析
    【解决方案2】:

    你应该明确地使用管道而不是指令

    类似的东西

    import { Pipe, PipeTransform } from '@angular/core';
    @Pipe({name: 'textOverflowLimit'})
    export class textOverflowLimithPipe implements PipeTransform {
      transform(value: string): string{
        if(value.length > 8)
          return value.substr(0,8)+'...';
        return value    
      }
    }
    

    并在模板中像这样使用它

    <td>{{"Some string" | textOverflowLimit }}</td>
    

    【讨论】:

    • 感谢您的回复!但我可以请你解释一下 - 为什么管道比指令更可取?
    • 这样就不需要直接访问 DOM,Angular2 不鼓励这样做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    相关资源
    最近更新 更多