在Angular 2 Component中的javascript中访问Typescript变量值 [英] Access Typescript variable value in javascript inside Angular 2 Component
问题描述
我在Angular 2中编写了一个可重用的组件,以便在我的应用程序中显示 Summernote
WYSIWYG编辑器。该组件接受3个输入参数,这些参数被设置为呈现的 textarea
的属性,作为id,name和最后一个用作正文。我的问题是在这个组件中我正在初始化Summernote插件并创建编辑器。 在这里,我不想硬编码选择器名称,并希望组件接收的动态值作为组件的输入参数。相关代码如下。
I have written a reusable component in Angular 2 to display the Summernote
WYSIWYG editor in my application. That component accepts 3 input parameters which are being set as attributes for a rendered textarea
as id, name and last one used as the body. My problem is that within this component I am initializing the Summernote plugin and creating the editor. Here, I do not want to hard code the selector name and want the dynamic values that the component received as the input parameters to the component. Relevant code is as follows.
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);
}
}
});
});
}
}
在这里,您可以看到我使用了 $(#body)
在 ngAfterViewInit
块内两次。我希望将其替换为 eid
变量。我尝试过 {{eid}}
但它不起作用并在浏览器控制台中抛出以下错误。
Here, you can see that I have used $("#body")
twice inside the ngAfterViewInit
block. I want this to be replaced by the eid
variable. I have tried {{eid}}
but it doesn't work and throws the following error in browser console.
EXCEPTION:语法错误,无法识别的表达式:#{{eid}}
this .eid
不能在这里使用,因为我们在javascript方法内部而不是打字稿。
this.eid
can't be used here either since we're inside the javascript method and not typescript.
我正在使用这个组件我的其他视图文件作为指令。
I'm using this component in my other view file as a directive.
< editor [body] =page.bodyeid =bodyename =body >< / editor>
组件中的模板
块已设置适当的动态值。只有javascript部分是我的问题。
The template
block in component is set properly with dynamic values. Only the javascript part is my issue.
我在这里还有其他方法吗?
Is there any other way I'm missing here?
P.S。到目前为止它的效果很好。我只是想让初始化完全动态化,这样我就可以在任何地方使用不同的ID。
P.S. So far it works great. I just want to make the initialization fully dynamic, so that I can use it anywhere with different IDs.
推荐答案
你可以尝试使用箭头函数而不是函数来保持相同的上下文。
You can try using arrow functions instead of function to keep the same context.
$(document).on("pageLoaded", () => {
console.log("pageLoaded");
$(this.eid).summernote({
height: '200px',
callbacks: {
onChange: (contents, $editable) => {
$(this.eid).val(contents);
}
}
});
});
}
这篇关于在Angular 2 Component中的javascript中访问Typescript变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!