gpt4 book ai didi

javascript - 返回 html 上的 Angular 2+ onmouseover 事件

转载 作者:行者123 更新时间:2023-11-28 14:27:10 24 4
gpt4 key购买 nike

我的 component.ts 中有一个方法,它返回一些像这样的 html:

someMethod() {
return `
<div>hello</div>
`;
}

我想返回一个带有鼠标悬停事件的 div,但似乎 (mouseenter)="myFunction()" 的 Angular 方式不起作用。可能是因为它返回的是 html 并且未编译。

someMethod() {
return `
<div (mouseenter)="myFunction()">hello</div>
`;
}

所以我发现执行常规的 javascript 方式 onmouseover="myFunction()" 确实会触发该函数:

someMethod() {
return `
<div onmouseover="myFunction()">hello</div>
`;
}

但问题是,我收到错误 Uncaught ReferenceError: myFunction is not Defined

myFunction() 是与 someMethod() 位于同一 component.ts 文件中的方法,它返回 html

我该如何解决我的问题,或者有其他方法可以写这个吗?

最佳答案

您的要求是渲染 Angular html 模板,该模板将用作字符串值(它可能来自数据库)。

坏消息

这不是你现在的做法。仅仅从绑定(bind)到 html 的 ts 文件中获取字符串值是行不通的,因为 Angular 在绑定(bind)时不会编译模板。

好消息

这在 Angular 中是可能的,但并不是一个简单的方法。如果您确实想实现此功能并广泛使用,那么绝对值得花时间在上面。

这里是RuntimeContentComponent,它有助于编译 Angular 模板

运行时内容.component.ts

import { 
Component,
ViewChild, ViewContainerRef, ComponentRef,
Compiler, ComponentFactory, NgModule, ModuleWithComponentFactories, ComponentFactoryResolver
} from '@angular/core';

import { CommonModule } from '@angular/common';

@Component({
selector: 'runtime-content',
template: `
<div>
<h3>Template</h3>
<div>
<textarea rows="5" [(ngModel)]="template"></textarea>
</div>
<button (click)="compileTemplate()">Compile</button>
<h3>Output</h3>
<div #container></div>
</div>
`
})
export class RuntimeContentComponent {

template: string = '<div>\nHello, {{name}}\n</div>';

@ViewChild('container', { read: ViewContainerRef })
container: ViewContainerRef;

private componentRef: ComponentRef<{}>;

constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private compiler: Compiler) {
}

compileTemplate() {

let metadata = {
selector: `runtime-component-sample`,
template: this.template
};

let factory = this.createComponentFactorySync(this.compiler, metadata, null);

if (this.componentRef) {
this.componentRef.destroy();
this.componentRef = null;
}
this.componentRef = this.container.createComponent(factory);
}

private createComponentFactorySync(compiler: Compiler, metadata: Component, componentClass: any): ComponentFactory<any> {
const cmpClass = componentClass || class RuntimeComponent { name: string = 'Denys' };
const decoratedCmp = Component(metadata)(cmpClass);

@NgModule({ imports: [CommonModule], declarations: [decoratedCmp] })
class RuntimeComponentModule { }

let module: ModuleWithComponentFactories<any> = compiler.compileModuleAndAllComponentsSync(RuntimeComponentModule);
return module.componentFactories.find(f => f.componentType === decoratedCmp);
}

}

链接

请参阅这篇优秀文章以获取完整的详细信息 - https://medium.com/@DenysVuika/dynamic-content-in-angular-2-3c85023d9c36

关于javascript - 返回 html 上的 Angular 2+ onmouseover 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52840020/

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