【问题标题】:How to use google Transliterate in angular 6?如何在 Angular 6 中使用谷歌音译?
【发布时间】: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


【解决方案1】:

请使用好的 livecyle 函数:AfterViewInit 等待 HTML 包含在 DOM 中。

在 TS 中

@ViewChild('sinhalaTextInput') sinhalaTextInput: ElementRef;

ngAfterViewInit() {
    ...
    google.setOnLoadCallback(() => this.onLoad()); // Don't lose "this" context 
}

private onLoad() {
    ...
    const elements = this.sinhalaTextInput.nativeElement;
    ...
}

在 HTML 中

<textarea #sinhalaTextInput [(ngModel)]="sinhalaText" id="sinhalaText" style="width:600px;height:200px"></textarea>

【讨论】:

  • 谢谢@Gilsdav。这是仅工作的应用程序组件。但我称另一个组件不起作用。这是显示为空的结果。
  • ERROR Error: Uncaught (in promise): ReferenceError: google is not defined ReferenceError: google is not defined
  • 是第一次调用“google”还是“onLoad”函数出错?你能试着把&lt;script type="text/javascript" src="https://www.google.com/jsapi"&gt;&lt;/script&gt;放在头上吗?
  • 我做到了。但不工作。但是在此工作中刷新此页面后。
  • @Prabuddha 如果解决方案对您有效,请考虑接受答案。
【解决方案2】:

下面的代码对我有用。

我做了两个改变

  1. 我已将以下代码移至脚本标记内的 index.html。
      google.load("elements", "1", {
          packages: "transliteration"
        });
  1. 在 ts 文件中更改了以下行。请遵循下面提到的完整代码。它的工作。
sinhalaControl.makeTransliteratable([elements.id]);

import { Component, ElementRef, ViewChild, OnInit, AfterViewInit } from '@angular/core';
declare var google: any;
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterViewInit {
  title = 'ng-transliteration';
  sinhalaText: string = '';
  constructor() {
  }
  @ViewChild('sinhalaTextInput', {static: false}) sinhalaTextInput: ElementRef;
  ngOnInit() {

  }
  ngAfterViewInit() {
    google.setOnLoadCallback(() => this.onLoad());
  }
  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 = this.sinhalaTextInput.nativeElement;
    sinhalaControl.makeTransliteratable([elements.id]);
    // const sinhalaControl = new google.elements.transliteration.TransliterationControl(sinhalOptions);
    // sinhalaControl.makeTransliteratable(this.sinhalaText);
   }

}
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>NgTransliteration</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  <script>
    google.load("elements", "1", {
      packages: "transliteration"
    });
  </script>
</head>
<body>
  <app-root></app-root>

</body>
</html>


<!---- app.component.html ---->


<textarea [(ngModel)]="sinhalaText" #sinhalaTextInput id="sinhalaText" style="width:600px;height:200px"></textarea>

【讨论】:

    【解决方案3】:

    我只是发布完整的组件作为答案

    export class HomeComponent implements OnInit {
    model = {
        left: true,
        middle: false,
        right: false
    };
    sinhalaText:"string"
    focus;
    focus1;
    constructor() { }
    
    ngOnInit() {}
    
    @ViewChild('sinhalaTextInput') sinhalaTextInput: ElementRef;
    ngAfterViewInit() {
        google.load("elements", "1", {
            packages: "transliteration"
          });   
    
    google.setOnLoadCallback(() => this.onLoad()); // Don't lose "this" context 
    }
    
    private onLoad() {
    const elements = this.sinhalaTextInput.nativeElement;
    var options = {
        sourceLanguage:
            google.elements.transliteration.LanguageCode.ENGLISH,
        destinationLanguage:
            [google.elements.transliteration.LanguageCode.TAMIL],
        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([elements]);
    
    }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-01
      • 2018-09-27
      • 2019-07-21
      • 2019-07-07
      • 2018-08-20
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多