use*_*579 12 javascript components angular
如果调用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?
}
}
Run Code Online (Sandbox Code Playgroud)
然后我将其声明为提供者,因此我可以调用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
}
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
Info您可以使用DynamicComponentLoaderGünter建议的方式动态添加此组件,而不是在组件中添加元素:
@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
});
}
}
Run Code Online (Sandbox Code Playgroud)
希望它对你有帮助,蒂埃里
| 归档时间: |
|
| 查看次数: |
33081 次 |
| 最近记录: |