我正在尝试创建一个div,然后在运行时将一个组件添加到该div中。我想知道我怎么能这样做。
这是我的组件html:
<p>
<label >name</label>
</p>
这是我的组件ts:
import { Component, OnInit} from '@angular/core';
@Component({
selector: 'app-newcomp',
templateUrl: './newcomp.component.html',
styleUrls: ['./newcomp.component.css']
})
export class NewcompComponent implements OnInit {
name: string;
constructor() {
}
ngOnInit() {
}
}
这就是所谓的
import { Component } from '@angular/core';
import { NewcompComponent } from './newcomp/newcomp.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
constructor() {
this.Newcomp();
}
Newcomp() {
const div = document.createElement('div');
document.body.appendChild(div);
<-- this is where the component is added to the div, how can i achieve this.
}
}
如果有人可以帮助我,我将不胜感激。 :)
我也知道这个例子很简单,但保持简单可以让答案清晰。
答案 0 :(得分:1)
import { Component } from '@angular/core';
import { NewcompComponent } from './newcomp/newcomp.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
component: Type<any>;
constructor() {
this.component = this.newcomp();
}
private newcomp() {
// use this method for logic
return NewcompComponent;
}
}
在app.component.html中添加:
<ng-container *ngComponentOutlet="component"></ng-container>
了解更多信息Angular's component outlet info&amp; Angular's dynamic component creation