2017-08-01 64 views
1

我正在将AngularJS 1.6组件迁移到Angular 4.3.2,并且需要在组件标签上强制执行id属性。然而,为了与现有的NG1组件NG2 +的工作,你需要降级他们:如何在角度2+降级的组件上强制使用id?

angular.module('myNg1module') 
    .directive('myComponent', downgradeComponent({component: MyComponent})) 

在编译的输出,这使得Angular generate a dynamic id它覆盖了你自己的id。例如输出将是:

<my-component id="NG2_UPGRADE_27_0"></my-component> 

我试了一下没有成功:

  • 设置在模板中id属性:<my-component id="my-id">但输出将简单地覆盖它;
  • 在模板中设置ID为[attr.id]<my-component [attr.id]="my-id">但这会被忽略。
+0

你可以创建一个plunker吗? –

回答

1

如果不是一个真正的解决方案是什么an Angular bug,这里是我用来覆盖产生id变通方法:

@Component({ 
    selector: 'my-component' 
}) 
class MyComponent implements OnInit { 
    @Input() id: string; 

    constructor(private el: ElementRef) {} 

    ngOnInit(): void { 
    this.el.nativeElement.id = this.id; 
    } 
} 

然后调用<my-component [id]="my-id">

它看起来是这样的重写生成的编号为won't have bad side-effects