在指令中覆盖标记值

Override tag value within directive

给定以下模板:

<p title>Hello World</p>

如何用指令中的另一个字符串替换 Hello World?

我尝试了以下但它不起作用:

@Directive({
  selector: '[title]'
})
export class TitleDirective{
  constructor(el: ElementRef, renderer: Renderer, private viewContainer: ViewContainerRef) {
    renderer.setText(el.nativeElement, 'Hello another world');
  }
}

我只能找到更改样式、属性或监听更改事件的示例,这些都没有帮助。

如果您只想更改 <p> 标签内的文本,您应该在控制器内创建一个局部变量并绑定到它。

.ts

private title = 'Hello World';

.html

<p>{{ title }}</p>

现在您可以更改控制器函数中的 title 变量,例如:

changeTitle(title: string) {
    this.title = title;
}

并调用 this.changeTitle('Hello another World');

回答我的问题:

您必须使用指令实现 OnInit 并传入给定节点,因为您必须等待 angular2:

设置属性(https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
@Directive({
  selector: '[title]'
})
export class TitleDirective implements OnInit{
  constructor(private el: ElementRef, private renderer: Renderer) {

  }

  ngOnInit(): void {
    this.renderer.setText(this.el.nativeElement.childNodes[0], 'Hello another world');
  }
}