2

I have a problem with initializing of some widget.

I am doing one project(Angular 2) and there must be widget. There it is

In index.html I place this:

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

And I have a component like this:

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());

    }
}

And html component:

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

<vk-component></vk-component>

I want to replace components with widget.

How to rewrite this on Angular 2:

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

In agularJS I used this:

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 );
            } );
        }
    }
}

] );

But i don't know how translate it to Angular 2

1 Answer 1

1

As I understand you need to add the script inside of the template. The solution is to create the script manually after the template is rendered, something like

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);
}

See this as an original answer on a similar question.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.