如何在Angular 2中初始化异物?

时间:2017-02-05 11:24:30

标签: javascript angular

我在初始化某个小部件时遇到了问题。

我正在做一个项目(Angular 2)并且必须有widget。 There it is

在index.html中我放置了这个:

<script type="text/javascript" src="//vk.com/js/api/openapi.js?139"></script>
<script type="text/javascript">
    VK.init({apiId: *******, onlyWidgets: true});
</script>

我有一个这样的组件:

import { Component, OnInit} from '@angular/core';
import { ActivatedRoute} from '@angular/router';
import { Response} from '@angular/http';
import { HttpService} from '../../services/http.service';


@Component({
    moduleId: module.id,
    selector: 'post-app',
    templateUrl: 'post.component.html',
    providers: [HttpService]
})
export class PostComponent implements OnInit {
    Post = [];
    id;
    constructor(private activateRoute: ActivatedRoute,private httpService: HttpService){
        this.id = activateRoute.snapshot.params['id'];
    }

    ngOnInit(){
        this.httpService.getOnePost(this.id).subscribe((data: Response) => this.Post=data.json());

    }
}

和html组件:​​

<div class="box-body">
    <div [innerHTML]="Post?.Blog?.Text"></div>
</div>

<vk-component></vk-component>

我想用widget替换组件。

如何在Angular 2上重写它:

<div id="vk_comments"></div>
<script type="text/javascript">
 VK.Widgets.Comments('vk_comments');
</script>

在agularJS中,我使用了这个:

app.directive( 'vkComments', [
'$window',
'$timeout',
function( $window, $timeout ){
    return {
        restrict: 'E',
        template: '<div id="vk_comments" ng-transclude post-url="{{url}}"></div>',
        scope: {
            readyToBind: '@'
        },
        replace: !0,
        transclude: !0,
        link: function( $scope, $element, $attr){
            $scope.$watch( 'readyToBind', function(){
                $timeout( function(){
                    $window.vkComment = VK.Widgets.Comments( 'vk_comments', { limit: 10, attach: '*', autoPublish: 1, mini: 1 }, location.href);
                }, 100 );
            } );
        }
    }
}

] );

但我不知道如何将它转化为Angular 2

1 个答案:

答案 0 :(得分:1)

据我了解,您需要在模板中添加脚本。解决方案是在呈现模板后手动创建脚本,如

constructor(private elementRef:ElementRef) {};

ngAfterViewInit() {
  var s = document.createElement("script");
  s.type = "text/javascript";
  s.innerText = "VK.Widgets.Comments('vk_comments');";
  this.elementRef.nativeElement.appendChild(s);
}

请参阅this作为类似问题的原始答案。