【发布时间】:2019-04-10 07:42:23
【问题描述】:
我使用了下面的代码。这在 index.html 中起作用
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Google Transliterate API
google.load("elements", "1", {
packages: "transliteration"
});
function onLoad() {
if (google.elements.transliteration.isBrowserCompatible()) {
var options = {
sourceLanguage: google.elements.transliteration.LanguageCode.ENGLISH,
destinationLanguage: [google.elements.transliteration.LanguageCode.SINHALESE],
shortcutKey: 'ctrl+g',
transliterationEnabled: true
};
// Create an instance on TransliterationControl with the required
// options.
var control =
new google.elements.transliteration.TransliterationControl(options);
// Enable transliteration in the textbox with id
// 'transliterateTextarea'.
control.makeTransliteratable(['transliterateTextarea']);
} else {
document.getElementById('errorDiv').innerHTML = 'Sorry! Your browser does not support transliteration';
}
}
google.setOnLoadCallback(onLoad);
</script>
以上代码更改后。
Ts 组件
import { Component, OnInit } from '@angular/core';
declare var google:any;
@Component({
选择器:'app-root',
templateUrl:'./app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'translate';
public sinhalaText: string;
constructor() {
google.load('elements','1', { packages: 'transliteration'});
google.setOnLoadCallback(this.onLoad);
}
ngOnInit() {}
onLoad() {
const sinhalOptions = {
sourceLanguage:
google.elements.transliteration.LanguageCode.ENGLISH,
destinationLanguage:
[google.elements.transliteration.LanguageCode.SINHALESE],
shortcutKey: 'ctrl+s',
transliterationEnabled: true
};
const tamilOptions = {
sourceLanguage:
google.elements.transliteration.LanguageCode.ENGLISH,
destinationLanguage:
[google.elements.transliteration.LanguageCode.TAMIL],
shortcutKey: 'ctrl+t',
transliterationEnabled: true
};
const sinhalaControl = new google.elements.transliteration.TransliterationControl(sinhalOptions);
const elements = document.getElementsByClassName('sinhalaText');> sinhalaControl.makeTransliteratable(elements);
// const sinhalaControl = new google.elements.transliteration.TransliterationControl(sinhalOptions);
// sinhalaControl.makeTransliteratable(this.sinhalaText);
}
}
html 组件
<textarea [(ngModel)]="sinhalaText" id="sinhalaText" style="width:600px;height:200px"></textarea>
index.html
<body>
<app-root></app-root>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</body>
这不起作用。
该代码适用于有角度的 index.html 文件。但我要求将代码嵌入到角度应用程序的组件内部。怎么样?
【问题讨论】:
-
如果将第二个脚本标签的代码放入角度组件的函数中会出现什么问题?我认为您唯一需要做的就是在 TS 文件的开头添加
declare var google: any;。 -
我已经用过这个但是不能用。
-
使用
AfterViewInit而不是构造函数。并使用ViewChild而不是 document.getElementsByClassName('sinhalaText')。 PS:您没有任何名为“sinhalaText”的类,但它是一个 ID。
标签: angular typescript google-api angular6 google-translate