Bas*_*ami 1 javascript typescript angular
我在 Angular 2 中编写了一个可重用的组件,以Summernote在我的应用程序中显示所见即所得编辑器。该组件接受 3 个输入参数,这些参数被设置为呈现textarea为 id、name 和最后一个用作正文的属性。我的问题是,在这个组件中,我正在初始化 Summernote 插件并创建编辑器。在这里,我不想对选择器名称进行硬编码,而是希望将组件接收的动态值作为组件的输入参数。相关代码如下。
import {Component, ElementRef, OnInit, EventEmitter, Input, Output, Inject, ComponentRef} from '@angular/core';
import {Http} from '@angular/http';
declare var $: any;
@Component({
selector: 'editor',
template: `<textarea id="{{eid}}" name="{{ename}}" class="form-control">{{body}}</textarea>`
})
export class EditorComponent {
@Input() body: string;
@Input() eid: string;
@Input() ename: string;
@Output() onContentChanged: EventEmitter<any>;
constructor(){}
ngAfterViewInit()
{
$(document).on("pageLoaded", function (){
console.log("pageLoaded");
$("#body").summernote({
height: '200px',
callbacks: {
onChange: function(contents, $editable) {
$("#body").val(contents);
}
}
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,你可以看到我在块$("#body")内使用了两次ngAfterViewInit。我希望将其替换为eid变量。我已经尝试过{{eid}},但它不起作用,并在浏览器控制台中抛出以下错误。
EXCEPTION: Syntax error, unrecognized expression: #{{eid}}
this.eid也不能在这里使用,因为我们在 javascript 方法而不是 typescript 中。
我在其他视图文件中使用此组件作为指令。
<editor [body]="page.body" eid="body" ename="body"></editor>
组件中的块template使用动态值正确设置。只有 javascript 部分是我的问题。
我在这里失踪还有其他方式吗?
PS 到目前为止效果很好。我只是想让初始化完全动态化,这样我就可以在任何具有不同 ID 的地方使用它。
您可以尝试使用箭头函数而不是函数来保持相同的上下文。
$(document).on("pageLoaded", () => {
console.log("pageLoaded");
$(this.eid).summernote({
height: '200px',
callbacks: {
onChange: (contents, $editable) => {
$(this.eid).val(contents);
}
}
});
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7158 次 |
| 最近记录: |