2017-08-01 68 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