【问题标题】:How to bind components to specific tag in angular?如何以角度将组件绑定到特定标签?
【发布时间】:2018-03-11 09:05:39
【问题描述】:

这是我正在开发的 angular-electron 应用程序的布局。

在动态区域或标签中我要根据side-nav component中的列表项的点击来绑定不同的组件。所有这些组件都放在MainComponent 中。动态是MainComponent 中的标签,我希望在其中拥有不同的组件。我想知道我怎样才能做到这一点。有什么技术可以做到这一点,或者这不可能吗?

【问题讨论】:

  • 对我来说这是一个类似标签的菜单。或者您可以将 ng-container 与 *ngTemplateOutlet="{{active}}" 和 ng-template-s 一起用于您的组件。

标签: angular angular2-routing dynamic-binding


【解决方案1】:

我不确定我是否完全理解您想要实现的目标,也许可以尝试发布一些代码。

这是一个带有在点击时创建的角度动态组件的 plunker。 https://plnkr.co/edit/p7VHB4?p=info 也许你可以从这里开始。

export default class DynamicComponent {  
  currentComponent = null;
  @ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) dynamicComponentContainer: ViewContainerRef;
  // component: Class for the component you want to create
  // inputs: An object with key/value pairs mapped to input name/input value
  @Input() set componentData(data: {component: any, inputs: any }) {
    if (!data) {
      return;
    }
    // Inputs need to be in the following format to be resolved properly
    let inputProviders = Object.keys(data.inputs).map((inputName) => {
      return {
        provide: inputName, 
        useValue: data.inputs[inputName]
      };
    });
    console.log(inputProviders);
    let resolvedInputs = ReflectiveInjector.resolve(inputProviders);
    // We create an injector out of the data we want to pass down and this components injector
    let injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.dynamicComponentContainer.parentInjector);
    // We create a factory out of the component we want to create
    let factory = this.resolver.resolveComponentFactory(data.component);
    // We create the component using the factory and the injector
    let component = factory.create(injector);
    //console.log("injector",inputProviders, resolvedInputs, factory, component);
    // We insert the component into the dom container
    let tempViewRef = this.dynamicComponentContainer.insert(component.hostView);
    let tempViewRefIndex = this.dynamicComponentContainer.indexOf(tempViewRef);
    // console.log(this.dynamicComponentContainer.get(tempViewRefIndex));
    console.log('**showNum Provider',this.dynamicComponentContainer);
    // Destroy the previously created component
    if(this.currentComponent){
      //this.currentComponent.destroy();
    }
    this.currentComponent = component;
  }

  constructor(private resolver: ComponentFactoryResolver) {
  }
}

确保在动态区域内添加锚组件

<div>
  <h2>Lets dynamically create some components!</h2>
  <button (click)="createHelloWorldComponent()">Create Hello World</button>
  <button (click)="createWorldHelloComponent()">Create World Hello</button>
  <dynamic-component [componentData]="componentData"></dynamic-component>
</div>  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    相关资源
    最近更新 更多