Angular 从可变角度渲染组件9
我可以做点什么吗Angular 从可变角度渲染组件9,angular,angular9,Angular,Angular9,我可以做点什么吗 @Component({ selector: "app-custom", template: "<h1>Hey, it's me!</h1>" }) export class CustomComponent { } @Component({ selector: "app-parent", template: "{{ someComponent }}" }) export class Parent { some
@Component({
selector: "app-custom",
template: "<h1>Hey, it's me!</h1>"
})
export class CustomComponent {
}
@Component({
selector: "app-parent",
template: "{{ someComponent }}"
})
export class Parent {
someComponent: CustomComponent;
constructor() {
this.someComponent = new CustomComponent();
}
}
@组件({
选择器:“应用程序自定义”,
模板:“嘿,是我!”
})
导出类自定义组件{
}
@组成部分({
选择器:“应用程序父级”,
模板:“{someComponent}}”
})
导出类父类{
someComponent:定制组件;
构造函数(){
this.someComponent=新的CustomComponent();
}
}
我想从变量渲染组件
@Component({
selector: "my-app",
template: "<ng-container #template></ng-container><p>Welcome</p>"
})
export class AppComponent implements OnInit {
@ViewChild("template", { static: true, read: ViewContainerRef })
private vcRef: ViewContainerRef;
private componentType: Type<HelloComponent>;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
ngOnInit() {
this.componentType = HelloComponent;
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(
this.componentType
);
const componentRef = this.vcRef.createComponent(componentFactory);
(<HelloComponent>componentRef.instance).name = "John";
}
}
这是示例代码,在我的代码中,我从contentchildren中获得了“自定义组件”,并希望使用我的更改来呈现它 您有一个组件:
@Component({
selector: 'hello',
template: `<h1>Hello {{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
public name: string = '';
}
@组件({
选择器:“你好”,
模板:`Hello{{name}}!`,
样式:[`h1{font-family:Lato;}`]
})
导出类HelloComponent{
公共名称:字符串=“”;
}
您希望使用变量渲染该组件
@Component({
selector: "my-app",
template: "<ng-container #template></ng-container><p>Welcome</p>"
})
export class AppComponent implements OnInit {
@ViewChild("template", { static: true, read: ViewContainerRef })
private vcRef: ViewContainerRef;
private componentType: Type<HelloComponent>;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
ngOnInit() {
this.componentType = HelloComponent;
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(
this.componentType
);
const componentRef = this.vcRef.createComponent(componentFactory);
(<HelloComponent>componentRef.instance).name = "John";
}
}
@组件({
选择器:“我的应用程序”,
模板:“欢迎光临”
})
导出类AppComponent实现OnInit{
@ViewChild(“模板”{static:true,read:ViewContainerRef})
私有vcRef:ViewContainerRef;
私有组件类型:类型;
构造函数(专用componentFactoryResolver:componentFactoryResolver){}
恩戈尼尼特(){
this.componentType=HelloComponent;
const componentFactory=this.componentFactoryResolver.resolveComponentFactory(
这是一个组件类型
);
const componentRef=此.vcRef.createComponent(componentFactory);
(componentRef.instance).name=“John”;
}
}
我们使用decorator找到“模板”容器,它将保存我们的组件,并将其作为对象引用(读取)。该对象将使我们能够创建和渲染组件
将获得用于创建我们的组件的工厂