gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:20:47 24 4
gpt4 key购买 nike

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

最佳答案

一个指令首先是一个类。

如果您可以手动获取构造函数所需的东西,您可以简单地执行以下操作:

const highlight = new HighlightDirective(...);

❗ Note that this is not standard Angular code. It is almost always preferable to let Angular do the work for you as you might accidentally escape its pipes and go rogue. If that happens, you might run into unexpected Angular behaviors as Angular doesn't know about what you're doing...

一个 3 年前的问题......我想知道是否有人仍在努力实现这一目标。 😊🤔

关于 Angular 2 : Add directive to dynamically created component(s),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49365011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com