角度动态组件 - 添加类和其他属性

时间:2018-01-10 13:59:19

标签: css angular dynamic attributes

我使用以下代码创建动态组件

import {
  Component, OnInit, ViewContainerRef, ViewChild, ViewChildren,
  ReflectiveInjector, ComponentFactoryResolver, ViewEncapsulation, QueryList, Input, AfterViewInit
} from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { forEach } from '@angular/router/src/utils/collection';
import { IComponent } from 'app/app.icomponent';


@Component({
  encapsulation: ViewEncapsulation.None,
  selector: 'dynamic-component',
  entryComponents: [HomeComponent, HighlevelSignalComponent],
  template: `
    <div #dynamicDiv [ngClass]="classFromMenu" >
     <ng-template #dynamicComponentContainer></ng-template>
    </div>
  `,
  styleUrls: [
    './dynamic-content.component.css'
  ],
})

export class DynamicComponent implements IComponent, OnInit, AfterViewInit {
  classFromMenu: any;
 @ViewChild('dynamicComponentContainer', { read: ViewContainerRef }) dynamicComponentContainer: ViewContainerRef;


  constructor(private resolver: ComponentFactoryResolver, private route: Router,
    private activatedRoute: ActivatedRoute, ) {

  }

  .......

  buildComponent(passedData) {
   // orderAndObjs has the data for creating the component

      this.orderAndObjs.forEach(obj => {
        var componentFactory = this.resolver.resolveComponentFactory(obj.component);
        var compRef = this.dynamicComponentContainer.createComponent(componentFactory);


     // compRef is the component that is created.
//Assuming the component that i am trying to create is <dynamic-component>. 


  //I want to add either a class or any other attribute like this
//<dynamic-component class="flex">
      });

    }
  }

}

动态组件创建完美,一切都按预期工作。但唯一的问题是我想为动态组件添加一个类,以便它可以

<dynamic-component class="dynamicClass">

感谢任何帮助:(

4 个答案:

答案 0 :(得分:9)

嗯..我通常将它添加到应该是entryComponent的组件的<ImageView android:id="@+id/background" android:scaleType="fitXY" android:src="@drawable/rain_drops" app:layout_constraintTop_toBottomOf="@id/toolbar" android:layout_width="match_parent" android:layout_height="match_parent"/> <!--android:alpha="0.5"/>--> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:layout_alignParentTop="true" android:elevation="6dp" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/> <android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:layout_below="@+id/toolbar" android:elevation="6dp" android:theme="@style/ThemeOverlay.AppCompat.Light" app:tabSelectedTextColor="@android:color/white" app:tabTextColor="@android:color/darker_gray"/> ...

selector

添加属性使用属性选择器:

selector: 'dynamic-component.someclass',
                            ^^^^^^^^^^^

我称之为 entryComponents的隐藏功能

但它的声明性方法并不能在运行时更改(实际上我们可以更改它)

答案 1 :(得分:6)

使用Renderer2提供程序执行高级DOM操作。考虑到它被注入,它是:

this.renderer2.addClass(compRef.location.elementRef, 'dynamicClass');

应该注意的是,根据动态元素如何附加到DOM,这可能是不必要的复杂化。

考虑到dynamicComponentContainer是真正的DOM元素而不是<ng-template>,动态组件的视图可以直接挂载到容器,从而消除了<dynamic-component>包装元素:

给出容器:

<div class="dynamicClass" #dynamicComponentContainer></div>

它将是:

var compRef = componentFactory.create(
  this.injector,
  [],
  this.dynamicComponentContainer.element.nativeElement
);

答案 2 :(得分:2)

在Angular 5/6中,使用@ angular / core中的Renderer2,您可以执行以下操作:

constructor(private resolver: ComponentFactoryResolver, private route: Router,
    private activatedRoute: ActivatedRoute, private renderer2: Renderer2) {

  }

buildComponent(passedData) {
  this.orderAndObjs.forEach(obj => {
    var componentFactory = this.resolver.resolveComponentFactory(obj.component);
    var compRef = this.dynamicComponentContainer.createComponent(componentFactory);
    this.renderer2.addClass(compRef.location.nativeElement, 'flex');
  });
}

答案 3 :(得分:-3)

该类将在dynamic-component.component.css文件中创建。

<强>动态componment.component.css

.dynamicClass {
    border: 1px solid red;
}

然后,您可以按照计划将此类添加到组件中,假设您的选择器是动态组件,它就是这样。

<dynamic-component class="dynamicClass">