Search code examples
javascriptangularjsangularng-upgrade

Angular 1 directive inside angular 2 application


We created an Angular 2 application using this awesome Angular2 Seed which works very well. So the question that I have is, how can I upgrade this Angular 1 directive:

import template from './sbgOutlineButton.html!text';

var app = angular.module('sbgOutlineButton', []);

app.directive('sbgOutlineButton', function() {
    let link = function(scope, element, attributes) {
        if (attributes.icon === undefined) {
            let materialIcon = element.find('i.material-icons');
            materialIcon.addClass('hidden');
        }

    };

    return {
        link: link,
        restrict: 'E',
        template: template,
        replace: true,
        transclude: true,
        scope: { icon: '@' }
    };
});

export default app;

So that I can use it in the following Angular 2 component:

import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { UpgradeAdapter } from '@angular/upgrade';

@Component({
    moduleId: module.id,
    selector: 'test-page',
    templateUrl: 'testpage.page.html',
    styleUrls: ['testpage.page.css']
})
export class TestPage implements OnInit {
    constructor() { }
    ngOnInit() { }
}

Do you guys maybe have any idea on how I will be able to accomplish this? Is it even possible? Because a lot of the other articles that I have found during my research suggests that your "base" application should be Angular 1...

Thanks in advance. Francois


Solution

  • You need to upgrade to angular2 by using "@angular/upgrade": "2.0.0-rc.4", Guide

    Because a lot of the other articles that I have found during my research suggests that your "base" application should be Angular 1...

    It's if you have a already angular 1 project and you want to upgrade to one. Angular2 don't need angular1 as base

    writing directive in angular2

    import { Directive, ElementRef, Input } from '@angular/core';
    @Directive({ selector: '[myHighlight]' })
    export class HighlightDirective {
        constructor(el: ElementRef) {
           el.nativeElement.style.backgroundColor = 'yellow';
        }
    }
    

    My First Attribute Directive

    Highlight me!

    import { Component } from '@angular/core';
    import { HighlightDirective } from './highlight.directive';
    @Component({
      selector: 'my-app',
      templateUrl: 'app/app.component.html',
      directives: [HighlightDirective]
    })
    export class AppComponent { }
    

    you Don't need to mix up angular1 into two..