[英]Angular 2 append Component dynamic to DOM or template
如果調用show(),我打算在DOM中添加一個動態組件。 我知道有一個使用ngIf或[hidden]的解決方案來隱藏它並將其用作指令,但我不是這個解決方案的粉絲,因為我不想在我的HTML中聲明它。
import {Component} from 'angular2/core';
import {InfoData} from '../../model/InfoData';
@Component({
selector: 'Info',
templateUrl: './components/pipes&parts/info.html',
styleUrls: ['./components/pipes&parts/info.css']
})
export class Info{
infoData: InfoData;
public show(infoData: InfoData) {
this.infoData= infoData;
document.body.appendChild(elemDiv); <----- Here?
}
}
然后我將其聲明為提供者,因此我可以調用show()。
import {Component} from 'angular2/core';
import {Info} from './components/pipes&parts/Info';
@Component({
selector: 'Admin',
templateUrl: './Admin.html',
styleUrls: ['./Admin.css'],
directives: [Info],
providers: [Info]
})
export class Admin {
constructor(private info: Info) {
info.show(); <---- append the Info Element to DOM
}
UPDATE
使用ViewContainerRef.createComponent()
有關完整示例,請參閱Angular動態選項卡,其中包含用戶單擊所選組件
原版的
很久以前就刪除了DynamicComponentLoader
您可以將DynamicComponentLoader用於此目的,但它有點麻煩並且存在與綁定相關的一些問題。
也可以看看:
我認為您不需要將Info
組件作為提供程序提供給其他組件。 我不確定它是否有效。 您可以利用Query
和QueryView
引用另一個中使用的組件:
@Component({
selector: 'Admin',
templateUrl: './Admin.html',
styleUrls: ['./Admin.css'],
directives: [Info]
})
export class Admin{
constructor(private @Query(Info) info: QueryList<Info>) {
info.first().show(); <---- append the Info Element to DOM
}
}
您可以使用Günter建議的DynamicComponentLoader
動態添加此組件,而不是在Info
組件中添加元素:
@Component({
selector: 'Info',
templateUrl: './components/pipes&parts/info.html',
styleUrls: ['./components/pipes&parts/info.css']
})
export class Info{
infoData: InfoData;
public show(infoData: InfoData) {
this.infoData= infoData;
// No need to add the element dynamically
// It's now part of the component template
// document.body.appendChild(elemDiv); <----- Here?
}
}
@Component({
selector: 'Admin',
//templateUrl: './Admin.html',
// To show where the info element will be added
template: `
<div #dynamicChild>
<!-- Info component will be added here -->
</div>
`,
styleUrls: ['./Admin.css'],
directives: [Info]
})
export class Admin{
constructor(private dcl: DynamicComponentLoader, private eltRef:ElementRef) {
this._dcl.loadIntoLocation(Info, this._el, 'dynamicChild')
.then(function(el) {
// Instance of the newly added component
});
}
}
希望它對你有幫助,蒂埃里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.