Angular 2: Add directive to dynamically created component(s)

左心房为你撑大大i 提交于 2019-12-08 18:18:25

问题


I came across the following Plunker to dynamically add and remove components. According to the above link and from many other SO posts, I know how to access Input and Output properties:

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

And I also have a directive "appFont".

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

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

How do I add this "appFont" directive to the new dynamically created component?


回答1:


This should probably do the work. You can get some HTML element from @Input() or simply target your element by getElement(s)By... Then you add attribute to component.

@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")
  }
}


来源:https://stackoverflow.com/questions/49365011/angular-2-add-directive-to-dynamically-created-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!