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

问题描述 投票:6回答:1

我遇到了以下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”指令添加到新动态创建的组件中?

angular angular-directive angular-components
1个回答
2
投票

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

@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")
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.