首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从变量Angular 9呈现组件

从变量Angular 9呈现组件
EN

Stack Overflow用户
提问于 2020-05-02 19:44:16
回答 1查看 391关注 0票数 1

我可以在Angular 9做点什么吗?

代码语言:javascript
复制
@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();
    }
}

我想从变量中渲染组件。

这是示例代码,在我的代码中,我从我的content子对象中获得了"custom-component“,并希望用我的更改来呈现它

EN

回答 1

Stack Overflow用户

发布于 2020-05-02 22:00:19

这是我对你想要做的事情的理解。

您有一个组件:

代码语言:javascript
复制
@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  public name: string = '';
}

您希望使用变量呈现该组件。

代码语言:javascript
复制
@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";
  }
}

我们使用@ViewChild装饰器来找到我们的“模板”容器,该容器将保存我们的组件,并将其作为ViewContainerRef对象引用(读取)。这个对象将使我们能够创建和呈现我们的组件。

ComponentFactoryResolver将获取用于创建我们的组件的工厂。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61558822

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档