Angular 2:向动态创建的组件添加指令

前端之家收集整理的这篇文章主要介绍了Angular 2:向动态创建的组件添加指令前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我遇到了以下 Plunker来动态添加删除组件.
根据以上链接和许多其他SO帖子,我知道如何访问输入和输出属性

this.compRef.instance.someProperty = 'someValue';
this.compRef.instance.someOutput.subscribe(val => doSomething());

而且我还有一个指令“appFont”.

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

@Directive({
  selector: '[appFont]'
})
export class HighlightDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.font = 'Calibri';
    }
}

如何将这个“appFont”指令添加到新动态创建的组件中?

解决方法

这可能应该做的工作.你可以从@Input()中获取一些HTML元素,或者只是通过getElement(s)来定位元素.然后你将属性添加到组件中.

@Component({
  selector: 'my-app',template: `<h1 id="header">{{title}}</h1>`
})
class AppComponent implements OnInit{
  @Input() el: ElementRef // or HTMLElement;
  title="hello world angular";

  ngOnInit() {
       el.nativeElement.createAttribute("appFont");
       // or 
       document.getElementById("header").createAttribute("appFont")
  }
}

猜你在找的Angularjs相关文章