angular 2降级指令不起作用

时间:2017-10-07 14:42:17

标签: angular

我正在尝试降级angular 2指令以与Angular 1.5应用程序一起使用。 我们能够降级Angular 2组件,但不能降级指令。

    import { Directive, ElementRef, Input, Renderer } from '@angular/core';
    import { UpgradeComponent } from '@angular/upgrade/static';

    @Directive({
        selector: 'myDir'
    })
    export class MyDirective {
        constructor(public el: ElementRef, public renderer: Renderer) {
            console.log('constructor');
        }
        ngOnInit() {
            console.log("onInit");
        }
    }

  angular.module(myapp)
            .directive('myDir', downgradeComponent({ component: MyDirective }));

当我尝试在Angular 1 app中使用该指令时,它没有触发构造函数或ngOnInit。

这就是我使用它的方式。

 <myDir></myDir>

1 个答案:

答案 0 :(得分:1)

你无法将@Directive从角度2降级到角度1.我们在遇到类似问题时遇到了困难,我们以不那么漂亮的方式解决了它。我们用ng-content作为模板降级@Component,然后用它包装元素(临时解决方案,一旦所有都在角度2,我们重构它)

所以我们有

@Component({
        selector: 'myDir',
        template: '<ng-content></ng-content>'
    })

这就是我们应用它的方式

<myDir><someOtherElementsWhereDirectiveShouldBeApplied></myDir>
相关问题