写一个angular的动态组件
时间: 2024-05-06 15:20:30 浏览: 16
以下是一个Angular的动态组件示例,该组件可以根据输入的组件类型动态创建并显示组件:
app.component.ts
```
import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { DynamicComponent } from './dynamic.component';
@Component({
selector: 'app-root',
template: `
<div #container></div>
<button (click)="createComponent('dynamic')">Create Dynamic Component</button>
`,
})
export class AppComponent {
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) {}
createComponent(type: string) {
// 根据组件类型获取组件工厂
const factory = this.resolver.resolveComponentFactory(DynamicComponent);
// 创建组件实例
const componentRef = this.container.createComponent(factory);
// 设置组件属性
componentRef.instance.type = type;
}
}
```
dynamic.component.ts
```
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-dynamic',
template: `
<div *ngIf="type">
Dynamic Component Type: {{ type }}
</div>
`,
})
export class DynamicComponent {
@Input() type: string;
}
```
在这个例子中,我们首先在`AppComponent`中使用`ViewChild`获取了一个`ViewContainerRef`引用,这个`ViewContainerRef`表示了一个可以动态添加组件的容器。然后,我们在`createComponent`方法中根据输入的组件类型获取了一个组件工厂,并使用`createComponent`方法创建了一个组件实例,并将其添加到了容器中。最后,我们还在`DynamicComponent`中添加了一个`Input`属性`type`,用于接收传递进来的组件类型。
使用这个动态组件的示例可以参考以下内容:
```
<app-root></app-root>
```
在页面中添加了一个按钮,当点击按钮时,会调用`AppComponent`中的`createComponent`方法创建一个`DynamicComponent`实例,并将其添加到页面中的容器中。这个`DynamicComponent`实例会根据传递进来的组件类型显示不同的内容。